Home > Software engineering >  Extract name of dataframe as string in R tidyverse
Extract name of dataframe as string in R tidyverse

Time:10-14

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?

CodePudding user response:

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
...

CodePudding user response:

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
....
  • Related