2015-09-13 158 views
1

我有一個數據框列表,每列數據框都有幾列。我的數據的一個例子是:數據框架列表 - 根據數據框架名稱添加一個新列

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

你可以通過所有具有lapply調用dataframes循環,像這樣的東西創建新列:

newlist = lapply(1:length(mylist), function(i){ 

    # Get the dataframe and the name 
    tmp_df = mylist[[i]] 
    tmp_name = names(mylist)[i] 

    # Create a new column with all NAs 
    tmp_df[,ncol(tmp_df) + 1] = NA 

    # Rename the newly created column 
    colnames(tmp_df)[ncol(tmp_df)] = tmp_name 

    # Return the df 
    return(tmp_df) 
}) 
+0

哇,這是快!非常感謝Lorenzo-Rossi – drgalindog

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) 
相關問題