可能,unlist两个列表,连接和子集数据
df[unlist(c(fixed, variable))]
Run Code Online (Sandbox Code Playgroud)
如果列表中有其他元素不是 'df' 中的列名,请使用 intersect
df[intersect(unlist(c(fixed, variable)), names(df))]
a a1 c1
1 7 8 1
2 3 1 5
3 8 5 4
4 7 5 6
5 2 5 6
Run Code Online (Sandbox Code Playgroud)
如果它是一个空的 data.frame,我们可以这样做
v1 <- unlist(c(fixed, variable))
df <- as.data.frame(matrix(numeric(), nrow = 0,
ncol = length(v1), dimnames = list(NULL, v1)))
str(df)
'data.frame': 0 obs. of 5 variables:
$ a : num
$ b : num
$ a1: num
$ b1: num
$ c1: num
Run Code Online (Sandbox Code Playgroud)
或者另一种选择是
df <- data.frame(setNames(rep(list(0), length(v1)), v1))[0,]
> str(df)
'data.frame': 0 obs. of 5 variables:
$ a : num
$ b : num
$ a1: num
$ b1: num
$ c1: num
Run Code Online (Sandbox Code Playgroud)
v1 <- c('a', 'd2', 'c', 'a1', 'd1', 'c1', 'e1')
set.seed(24)
df <- as.data.frame(matrix(sample(1:9, 5 * length(v1),
replace = TRUE), ncol = length(v1), dimnames = list(NULL, v1)))
Run Code Online (Sandbox Code Playgroud)