2016-09-21 53 views
1

我有32個dataframes,我需要獲得對每個數據幀包含的一些其他dataframes'列的總和一個新的數據幀。新數據幀cointaning總和,R

讓我寫一個例子,2個dataframes更清晰:

df1 <- data.frame(1:5,2:6,3:7, 4:8) 
colnames(df1) <- c("one", "two", "three", "four") 
df2 <- data.frame(4:8, 5:9, 6:10, 7:11) 
colnames(df2) <- c("one", "two", "three", "four") 

我想獲得一個數據幀df1a,其中第1列1列和第3數據框df1的總和,第2列是相同的,沒有變化。另外我希望第4列的輸出放在第一位。

我知道我可以寫這樣的代碼:

df1a <- data.frame(df1$four, df1$one+df1$three, df1$two) 
colnames(df1a) <- c("four", "1+3", "two") 

但在我看來,很長時間寫的每一個數據幀,因爲在我的真實的數據我已經做各20列的32個dataframes。

我把它們放在一個列表:

listdf <- list(df1, df2) 

我想我需要去申請一些循環或一些與應用,但我想不出如何。

的,我想獲得DF1到df1a的代碼示例:

df1 
    one two three four 
1 1 2  3 4 
2 2 3  4 5 
3 3 4  5 6 
4 4 5  6 7 
5 5 6  7 8 

df1a <- data.frame(df1$four, df1$one+df1$three, df1$two) 
colnames(df1a) <- c("four", "1+3", "two") 
df1a 
    four 1+3 two 
1 4 4 2 
2 5 6 3 
3 6 8 4 
4 7 10 5 
5 8 12 6 
+1

見格里高爾與列表工作答案[此帖](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) data.frames。我的答案給出了一個很好的快捷方式來檢索data.frames的命名列表。 – lmo

+1

@RonakShah,增加了一個例子 – Francesco

回答

1

參見代碼中的註釋。本質上,您編寫的功能應該在每個數據幀上執行,並使用它lapplysapply在每個數據幀上執行此操作。由於您將這些data.frames放入列表中,因此使用lapplysapply非常方便。

df1 <- data.frame(1:5,2:6,3:7, 4:8) 
colnames(df1) <- c("one", "two", "three", "four") 
df2 <- data.frame(4:8, 5:9, 6:10, 7:11) 
colnames(df2) <- c("one", "two", "three", "four") 

# Create a function which holds commands to be used on a single data.frame 
operationsPerDF <- function(x) { 
    data.frame(four = x$four, onepthree = x$one + x$three, two = x$two) 
} 

# You can manually gather data.frames into a list. 
lapply(list(df1, df2), FUN = operationsPerDF) 

# Or find data.frames by a pattern, collect them into a list... 
list.dfs <- sapply(ls(pattern = "df"), get, simplify = FALSE) 

# ... and perform the above operation, one data.frame at a time 
lapply(list.dfs, FUN = operationsPerDF) 

$df1 
    four onepthree two 
1 4   4 2 
2 5   6 3 
3 6   8 4 
4 7  10 5 
5 8  12 6 

$df2 
    four onepthree two 
1 7  10 5 
2 8  12 6 
3 9  14 7 
4 10  16 8 
5 11  18 9 
+0

我應用了這個函數,並使用了'lapply(nameofmylist,FUN = operationsPerDF)',但是我失去了列表中的數據框名稱。有沒有辦法避免這種損失? – Francesco

+0

@Francesco你如何構建'nameofmylist'?這可能是擦除名稱的步驟。 –

+0

這樣:'listdf < - list(df1,df2)'。也許我應該說出來? – Francesco