R:从函数向数据框添加新列

时间:2017-08-31 14:05:58

标签: r function dataframe tibble

我有很多类似的东西:

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"))

为了测试,我们再添加一个:

dftest2_tw <- dftest_tw

我有我的df列表:

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

我期待的是:

1-添加名为Twitter.name

的新列

2-用df 名称填充列,所有这些都在函数中。以下代码适用于逐个采用的每个df:

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

期望的结果是:

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

当谈到写一个函数以后应用于我所有的df(超过100)时,我无法实现它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我们可以使用Polinomio([], len(self.termos)选项。使用tidyverse获取多个字符串对象的值,然后使用mget中的map2获取purrr的每个数据集中的新列&#39; Twitter.name &#39; myUserList`

的相应字符串元素
list

如果我们需要修改全局环境中的对象,请使用library(tidyverse) lst <- mget(myUserList) %>% map2(myUserList, ~mutate(.data = .x, Twitter.name = .y))

list2env