R: add a new column to dataframes from a function

181 views Asked by At

I have many tibbles similar to this:

dftest_tw <- structure(list(text = c("RT @BitMEXdotcom: A new high: US$500M turnover in the last 24 hours, over 80% of it on $XBTUSD. Congrats to the team and thank you to our u…", 
"RT @Crowd_indicator: Thank you for this nice video, @Nicholas_Merten", 
"RT @Crowd_indicator: Review of #Cindicator by DataDash: t.co/D0da3u5y3V"
), Tweet.id = c("896858423521837057", "896858275689398272", "896858135314538497"
), created.date = structure(c(17391, 17391, 17391), class = "Date"), 
    created.week = c(33, 33, 33)), .Names = c("text", "Tweet.id", 
"created.date", "created.week"), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

For testing, we add another one:

dftest2_tw <- dftest_tw

I have this list of my df:

myUserList <- ls(,pattern = "_tw")

What I am looking to do is:

1- add a new column named Twitter.name

2- fill the column with the df name, all this in a function. The following code works for each df taken one by one:

dftest_tw %>% rowwise() %>% mutate(Twitter.name = myUserList[1])

The desired result is this:

MyRes <- structure(list(text = c("RT @BitMEXdotcom: A new high: US$500M turnover in the last 24 hours, over 80% of it on $XBTUSD. Congrats to the team and thank you to our u…", 
"RT @Crowd_indicator: Thank you for this nice video, @Nicholas_Merten", 
"RT @Crowd_indicator: Review of #Cindicator by DataDash: t.co/D0da3u5y3V"
), Tweet.id = c("896858423521837057", "896858275689398272", "896858135314538497"
), created.date = structure(c(17391, 17391, 17391), class = "Date"), 
    created.week = c(33, 33, 33), retweet = c(0, 0, 0), custom = c(0, 
    0, 0), Twitter.name = c("dftest_tw", "dftest_tw", "dftest_tw"
    )), .Names = c("text", "Tweet.id", "created.date", "created.week", 
"retweet", "custom", "Twitter.name"), class = c("rowwise_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L))

When it comes to write a function to be thereafter been applied to all my df (more than 100), I can't achieve it. Any help would be appreciated.

1

There are 1 answers

6
akrun On BEST ANSWER

We can use tidyverse options. Get the value of multiple string objects with mget, then with map2 from purrr, create the new column 'Twitter.name in each dataset of the list with corresponding string element of 'myUserList`

library(tidyverse) 
lst <- mget(myUserList) %>% 
          map2(myUserList,  ~mutate(.data = .x, Twitter.name = .y))

If we need to modify the objects in the global environment, use list2env

list2env(lst, envir = .GlobalEnv)