我想为列表中的每个数据框将数据框名称添加到列中的所有行。
虚拟数据:
test_df <- data.frame(x = 1:5, y = c("a","b","c","d","e"))
我要结束的是:
x y ref
1 a test_df
2 b test_df
3 c test_df
4 d test_df
5 e test_df
原因是我稍后将重新绑定多个数据帧,并且希望能够过滤值来自哪个数据帧。我尝试了以下方法:
library(dplyr)
test <- function(df) {
df <- df %>%
mutate(ref = deparse(substitute(df)))
return(df)
}
但这只会在每行中创建一个名为ref的列,其值为“ df”。与dplyr的任何建议将不胜感激。还是有办法直接在rbind-call中创建此列?
使用dplyr
,请尝试以下操作:
library(lazyeval)
test <- function(df) {
df <- df %>% mutate(ref = expr_label(df))
return(df)
}
test(test_df)
x y ref
1 a `test_df`
2 b `test_df`
3 c `test_df`
4 d `test_df`
5 e `test_df`
另外,这也可以,但是不使用dplyr
:
test2 <- function(df) {
df$ref <- deparse(substitute(df))
return(df)
}
test2(test_df)
x y ref
1 1 a test_df
2 2 b test_df
3 3 c test_df
4 4 d test_df
5 5 e test_df
要使它与数据帧列表一起使用,lapply
由于lapply
工作原理而比较棘手,但是以下变通方法起作用:
test_df <- data.frame(x = 1:5, y = c("a","b","c","d","e"))
test_df2 <- data.frame(x = 11:15, y = c("aa","bb","cc","dd","ee"))
在这里,我创建一个数据框的命名列表:
dfs <- setNames(list(test_df, test_df2), c("test_df", "test_df2"))
dfs
$test_df
x y
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
$test_df2
x y
1 11 aa
2 12 bb
3 13 cc
4 14 dd
5 15 ee
现在,我更改辅助函数以将该名称作为参数:
test3 <- function(df, nm) {
df$ref <- nm
return(df)
}
在这里,我仅将名称传递给我,lapply
并从dfs
上面定义的命名列表中检索每个数据框。
lapply(names(dfs), function(x) test3(dfs[[x]], x))
[[1]]
x y ref
1 1 a test_df
2 2 b test_df
3 3 c test_df
4 4 d test_df
5 5 e test_df
[[2]]
x y ref
1 11 aa test_df2
2 12 bb test_df2
3 13 cc test_df2
4 14 dd test_df2
5 15 ee test_df2
那不是最优雅的方式,但是它可行。
话虽如此,如果您想将数据帧组合为一个单一的数据帧,@markus的using推荐就没有什么可添加的了bind_rows
,例如
bind_rows(dfs, .id="ref")
ref x y
1 test_df 1 a
2 test_df 2 b
3 test_df 3 c
4 test_df 4 d
5 test_df 5 e
6 test_df2 11 aa
7 test_df2 12 bb
8 test_df2 13 cc
9 test_df2 14 dd
10 test_df2 15 ee
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句