我有一个包含53个数据帧的列表,我想为每个数据帧添加不同的列,例如第一个数据框包含6列和80行,我想添加一个包含" Week1"的新列。第二个数据框有6列和60行,我想添加一个包含" Week2"的新列。等等。
我有一个包含字符串的向量"第1周和第34天;到第53周和第34周,但我不知道如何将此特定列添加到列表中的每个数据框。
到目前为止,我尝试使用lapply函数编写循环和方法,但我没有解决它。我很感激你的帮助! 到目前为止我尝试的两种方法的代码下面。 循环:
for(i in 1:53){
if(mylist[i]==name[i]){
mylist[i] <- cbind(mylist[i],name[i])
}
i <- i+1
}
和lapply的方法:
f <- function(i){
cbind(mylist,name)
}
myfilelist <- lapply(myfilelist,f)
答案 0 :(得分:4)
您可以尝试使用Map
和cbind
,如下所示:
x <-data.frame(matrix(1:4,2))
myfilelist <-list(x,x)
week <-paste0("week",1:2) #53 in your case
Map(cbind, myfilelist, week=as.list(week))
[[1]]
X1 X2 week
1 1 3 Week1
2 2 4 Week1
[[2]]
X1 X2 week
1 1 3 Week2
2 2 4 Week2
如果您想自动创建&#34;第1周&#34;,&#34;第2周&#34;的矢量,请使用:
week <-lapply(seq(1:length(myfilelist)),function(i) paste0("Week",i))
Map(cbind, myfilelist, week=week)
答案 1 :(得分:3)
另一个想法(使用@PLapointe的数据)
library(purrr)
library(dplyr)
map2(myfilelist,
seq_along(myfilelist),
~ mutate(.x, week = paste0("week", .y)))
给出了:
#[[1]]
# X1 X2 week
#1 1 3 week1
#2 2 4 week1
#
#[[2]]
# X1 X2 week
#1 1 3 week2
#2 2 4 week2
正如@alistaire所提到的,使用devel版本的purrr
( v0.2.2.9000 ),您可以这样做:
imap(myfilelist, ~mutate(.x, week = paste0('week', .y)))
来自文档:
imap_xxx(x, ...)
是一个索引地图,如果map2(x, names(x), ...)
有名称,则为x
的简写,如果不是,则为map2(x, seq_along(x), ...)
。 如果您需要计算值和值,这非常有用 元素的位置
答案 2 :(得分:1)
如果您对for loop
解决方案感兴趣,这里有一个,我假设数据帧数和周数相同:
df1 <- data.frame(x=1:10,y=2:11)
df2 <- data.frame(x=1:20,y=2:21,c=letters[1:20])
lis <- list(df1,df2)
vect <- c("week1","week2")
for(i in 1:length(lis)){
week <-rep(vect[i],max(lengths(lis[[i]])))
lis[[i]] <- cbind(lis[[i]],week)
}
<强>输出强>:
> lis
[[1]]
x y week
1 1 2 week1
2 2 3 week1
3 3 4 week1
4 4 5 week1
5 5 6 week1
6 6 7 week1
7 7 8 week1
8 8 9 week1
9 9 10 week1
10 10 11 week1
[[2]]
x y c week
1 1 2 a week2
2 2 3 b week2
3 3 4 c week2
4 4 5 d week2
5 5 6 e week2
6 6 7 f week2
7 7 8 g week2
8 8 9 h week2
9 9 10 i week2
10 10 11 j week2
11 11 12 k week2
12 12 13 l week2
13 13 14 m week2
14 14 15 n week2
15 15 16 o week2
16 16 17 p week2
17 17 18 q week2
18 18 19 r week2
19 19 20 s week2
20 20 21 t week2
>
答案 3 :(得分:1)
另一种选择(使用@PLapointe的数据):
f <- function(i){
myfilelist[[i]]$week <- paste0('Week_',i)
myfilelist[[i]]
}
lapply(seq_along(myfilelist), f)
给出:
[[1]]
X1 X2 week
1 1 3 Week_1
2 2 4 Week_1
[[2]]
X1 X2 week
1 1 3 Week_2
2 2 4 Week_2