3

I want to add a column to a dataframe containing its own name as a string. (This is for inclusion in a function that will bind several of them together...)

Based on this old SO post and my understanding of magrittr pipes I thought this would work:

data(iris)
iris %>%
  mutate(df = deparse(substitute(.))

But that just adds a column called "df" populated with full stops! The desired output is the string "iris" in every row of that df column. Can anyone set me right?

0

2 Answers 2

3

If we have a function, it can be done

library(dplyr)
fun1 <- function(data) {
       datanm <- deparse(substitute(data))
       data %>%
         mutate(df = datanm)
}

-testing

> fun1(iris)
 Sepal.Length Sepal.Width Petal.Length Petal.Width    Species   df
1            5.1         3.5          1.4         0.2     setosa iris
2            4.9         3.0          1.4         0.2     setosa iris
3            4.7         3.2          1.3         0.2     setosa iris
4            4.6         3.1          1.5         0.2     setosa iris
5            5.0         3.6          1.4         0.2     setosa iris
6            5.4         3.9          1.7         0.4     setosa iris
7            4.6         3.4          1.4         0.3     setosa iris
...
Sign up to request clarification or add additional context in comments.

Comments

2

Maybe this is also helpful:

library(dplyr)
bind_rows(list(iris = iris), .id = 'df')
      df Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1   iris          5.1         3.5          1.4         0.2     setosa
2   iris          4.9         3.0          1.4         0.2     setosa
3   iris          4.7         3.2          1.3         0.2     setosa
4   iris          4.6         3.1          1.5         0.2     setosa
5   iris          5.0         3.6          1.4         0.2     setosa
6   iris          5.4         3.9          1.7         0.4     setosa
7   iris          4.6         3.4          1.4         0.3     setosa
8   iris          5.0         3.4          1.5         0.2     setosa
9   iris          4.4         2.9          1.4         0.2     setosa
....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.