2017-08-02 18 views
0

我有一個矩陣有多個不同名稱的列,但其中一些是相同的,我想將它們組合在一起,然後取這些列的平均值。如何將兩個不同列中的值與相同的名稱組合起來?

基本上,

Lung Lung Lung Heart Heart Heart Kidney Kidney Kidney Liver Liver Liver 
3  7 9  1  2  1  8  9  12  15 17 19 

我想上面的矩陣看起來像這樣

Lung Heart Kidney Liver 
3  1  8  15 
7  2  9  17 
9  1  12 19 

於是我打算讓每列的平均值(肺,心臟等)

所以,如果你建議一個代碼來計算具有相同名稱的列的方法,但是沒有將它們組合起來也是可以的。

回答

2

我們可以使用split

data.frame(lapply(split.default(df1, names(df1)), unlist, use.names = FALSE)) 
# Heart Kidney Liver Lung 
#1  1  8 15 3 
#2  2  9 17 7 
#3  1  12 19 9 
1

這裏是matrix的方法來組織值代入列和setNames添加變量名。請注意,這要求具有相同名稱的變量具有相同的大小並且相鄰。

setNames(data.frame(matrix(unlist(dat), 3)), unique(names(dat))) 
    Lung Heart Kidney Liver 
1 3  1  8 15 
2 7  2  9 17 
3 9  1  12 19 

此外,該解決方案可與data.frame而不是一個矩陣,因爲這是在問題提出的結構,但相同的代碼將不會受到任何影響矩陣工作。

數據

dat <- 
structure(list(Lung = 3L, Lung = 7L, Lung = 9L, Heart = 1L, Heart = 2L, 
    Heart = 1L, Kidney = 8L, Kidney = 9L, Kidney = 12L, Liver = 15L, 
    Liver = 17L, Liver = 19L), .Names = c("Lung", "Lung", "Lung", 
"Heart", "Heart", "Heart", "Kidney", "Kidney", "Kidney", "Liver", 
"Liver", "Liver"), class = "data.frame", row.names = c(NA, -1L 
)) 
相關問題