Robert Hickman
Robert Hickman

Reputation: 907

Calling a data.frame from global.env and adding a column with the data.frame name

I have a dataset consisting of pairs of data.frames (which are almost exact pairs, but not enough to merge directly) which I need to munge together. Luckily, each df has an identifier for the date it was created which can be used to reference the pair. E.g.

df_0101 <- data.frame(a = rnorm(1:10),
                      b = runif(1:10))

df_0102 <- data.frame(a = rnorm(5:20),
                      b = runif(5:20))

df2_0101 <- data.frame(a2 = rnorm(1:10),
                      b2 = runif(1:10))

df2_0102 <- data.frame(a2 = rnorm(5:20),
                      b2 = runif(5:20))

Therefore, the first thing I need to do is mutate a new column on each data.frame consisting of this date (01_01/ 01_02 / etc.) i.e.

df_0101 <- df_0101 %>%
    mutate(df_name = "df_0101")

but obviously in a programmatic manner.

I can call every data.frame in the global environment using

l_df <- Filter(function(x) is(x, "data.frame"), mget(ls()))

head(l_df)
$df_0101
            a          b
1   0.7588803 0.17837296
2  -0.2592187 0.45445752
3   1.2221744 0.01553190
4   1.1534353 0.72097071
5   0.7279514 0.96770448

$df_0102
             a          b
1  -0.33415584 0.53597308
2   0.31730849 0.32995013
3  -0.18936533 0.41024220
4   0.49441962 0.22123885
5  -0.28985964 0.62388478

$df2_0101
           a2        b2
1  -0.5600229 0.6283224
2   0.5944657 0.7384586
3   1.1284180 0.4656239
4  -0.4737340 0.1555984
5  -0.3838161 0.3373913

$df2_0102
            a2         b2
1  -0.67987149 0.65352466
2   1.46878953 0.47135011
3   0.10902751 0.04460594
4  -1.82677732 0.38636357
5   1.06021443 0.92935144

but no idea how to then pull the names of each df down into a new column on each. Any ideas?

Thanks for reading,

Upvotes: 1

Views: 450

Answers (1)

akrun
akrun

Reputation: 886998

We can use Map in base R

Map(cbind, names = names(l_df), l_df)

If we are going by the tidyverse way, then

library(tidyverse)
map2(names(l_df), l_df, ~(cbind(names = .x, .y)))

Also, this can be created a single dataset with bind_rows

bind_rows(l_df, .id = "names")

Upvotes: 1

Related Questions