数据框列表 - 根据数据框名称添加新列

时间:2015-09-13 19:34:17

标签: r list lapply

我有一个数据框列表,每个数据框都有几列。我的数据的一个例子可能是:

Ind_ID<-rep(1:15)
Mun<-sample(15)
T_i<-paste0("D",rep(1:5))
data<-cbind(Ind_ID,Mun,T_i)
data<-data.frame(data)
mylist<-split(data,data$T_i)
str(mylist)

List of 5
 $ D1:'data.frame':     3 obs. of  3 variables:
  ..$ Ind_ID: Factor w/ 15 levels "1","10","11",..: 1 12 3
  ..$ Mun   : Factor w/ 15 levels "1","10","11",..: 3 10 7
  ..$ T_i   : Factor w/ 5 levels "D1","D2","D3",..: 1 1 1
 $ D2:'data.frame':     3 obs. of  3 variables:
  ..$ Ind_ID: Factor w/ 15 levels "1","10","11",..: 8 13 4
  ..$ Mun   : Factor w/ 15 levels "1","10","11",..: 14 11 5
  ..$ T_i   : Factor w/ 5 levels "D1","D2","D3",..: 2 2 2
...
 $ D5:'data.frame':     3 obs. of  3 variables:
  ..$ Ind_ID: Factor w/ 15 levels "1","10","11",..: 11 2 7
  ..$ Mun   : Factor w/ 15 levels "1","10","11",..: 4 12 2
  ..$ T_i   : Factor w/ 5 levels "D1","D2","D3",..: 5 5 5

我想添加一个与数据框同名的新列。我的预期输出是:

$D1
   Ind_ID Mun T_i  D1
1       1  11  D1 NA
6       6   4  D1 NA
11     11  15  D1 NA

$D2
   Ind_ID Mun T_i  D2
2       2   8  D2 NA
7       7   5  D2 NA
12     12  13  D2 NA

....

$D5
   Ind_ID Mun T_i  D5
5       5  12  D5 NA
10     10   6  D5 NA
15     15  10  D5 NA

我失败的尝试包括:

nam<-as.list(names(mylist))
fun01 <- function(x,y){cbind(x, y = rep(1, nrow(x)))}
a1<-lapply(mylist, fun01,nam)
str(a1) # This generates a new column with the name "y" in all cases

fun02 <- function(x,y){x= cbind(x, a = rep(1, nrow(x)));names(x)[4] <- y}
a2<-lapply(mylist, fun02,nam)
str(a2) # It changes the data frames

有任何帮助吗?提前致谢

2 个答案:

答案 0 :(得分:2)

您可以通过lapply调用遍历所有数据框,并使用以下内容创建新列:

.sidebar-nav {
/* position: absolute; */ No use.
width: 250px;
margin: 0 auto; /*Set the margin as per your requirement. eg; 50px auto 0px*/
padding: 0;
list-style: none;
border: 1px solid red; /*just to highlight*/
}

答案 1 :(得分:2)

选项1:您可以使用Map()。首先,我们可以为迭代编写一个小函数。

f <- function(df, nm) cbind(df, setNames(data.frame(NA), nm))
Map(f, mylist, names(mylist))

选项2:您可以危险地生活并且

Map("[<-", mylist, names(mylist), value = NA)