這裏的另一種選擇。使用@ Matthew的答案中的「x」,您可以使用strtim
從您的姓名創建您的類別,然後使用sapply
跨過這些類別進行彙總。
mymatch <- strtrim(names(x), 3)
sapply(unique(mymatch), function(y) rowSums(x[, mymatch == y, drop = FALSE]))
# 0.4 0.5 0.6
# DAWO 5 0 8
# DRWO 6 3 1
# DHWO 3 0 0
另外,使用原始數據,你只需要一點點小心,記住要放棄你「的Class1」列取rowSums
時:
mymatch <- strtrim(names(mydf), 3)[-1]
cbind(mydf[1],
sapply(unique(mymatch),
function(y) rowSums(mydf[-1][, mymatch == y, drop = FALSE])))
# Class1 0.4 0.5 0.6
# 1 DAWO 5 0 8
# 2 DRWO 6 3 1
# 3 DHWO 3 0 0
最後,還有經典「reshape2」 的方式,涉及melt
和*cast
:
> library(reshape2)
> Stacked <- melt(mydf)
Using Class1 as id variables
> dcast(Stacked, Class1 ~ strtrim(variable, 3), fun.aggregate=sum)
Class1 0.4 0.5 0.6
1 DAWO 5 0 8
2 DHWO 3 0 0
3 DRWO 6 3 1
在過去的兩個例子,mydf
定義爲:
mydf <- structure(list(Class1 = structure(c(1L, 3L, 2L), .Label = c("DAWO",
"DHWO", "DRWO"), class = "factor"), `0.438` = c(2L, 1L, 1L),
`0.441` = c(2L, 1L, 2L), `0.442` = c(0L, 3L, 0L), `0.444` = c(1L,
1L, 0L), `0.545` = c(0L, 1L, 0L), `0.546` = c(0L, 1L, 0L),
`0.548` = c(0L, 1L, 0L), `0.609` = c(1L, 0L, 0L), `0.651` = c(1L,
0L, 0L), `0.652` = c(5L, 1L, 0L), `0.655` = c(1L, 0L, 0L)),
.Names = c("Class1", "0.438", "0.441", "0.442", "0.444", "0.545", "0.546",
"0.548", "0.609", "0.651", "0.652", "0.655"), class = "data.frame",
row.names = c(NA, -3L))