如果我正确理解了您的问题,您可能只需要从“reshape2”包中melt
进行探索。dcast
使用@zx8754 的示例数据,尝试以下操作:
library(reshape2)
### Make the data into a "long" format
dfL <- melt(df, id.vars=c("Code", "Cond"))
### Split the existing "variable" column.
### Here's one way to do that.
dfL <- cbind(dfL, setNames(
do.call(rbind.data.frame, strsplit(
as.character(dfL$variable), "(?=\\d)", perl=TRUE)),
c("var", "time")))
### This is what the data now look like.
head(dfL)
# Code Cond variable value var time
# 1 BAX-011 3 bf1 CR bf 1
# 2 BAX-012 3 bf1 CR bf 1
# 3 BAX-013 3 bf1 CR bf 1
# 4 BAX-011 3 bf2 FA bf 2
# 5 BAX-012 3 bf2 FA bf 2
# 6 BAX-013 3 bf2 HIT bf 2
### Use `dcast` to aggregate the data.
### The default function is "length" which is what you're looking for.
dcast(dfL, Code + Cond ~ var + value, value.var="value")
# Aggregation function missing: defaulting to length
# Code Cond bf_CR bf_FA bf_HIT bm_CR bm_FA bm_FR bm_HIT
# 1 BAX-011 3 1 2 1 1 2 1 0
# 2 BAX-012 3 1 2 1 0 2 1 1
# 3 BAX-013 3 1 1 2 0 2 1 1
从那里,您可以随时merge
或cbind
相关栏目一起获得完整的data.frame
.
更新
为了避免被视为“reshape2”的粉丝,这里有一个基本的 R 方法。我希望它也能说明我为什么在这种情况下选择“reshape2”路线:
X <- grep("^bf|^bm", names(df))
df[X] <- lapply(df[X], as.character)
dfL <- cbind(dfL, setNames(
do.call(rbind.data.frame, strsplit(
as.character(dfL$ind), "(?=\\d)", perl=TRUE)),
c("var", "time")))
dfL$X <- paste(dfL$var, dfL$values, sep ="_")
dfA <- aggregate(values ~ Code + Cond + X, dfL, length)
reshape(dfA, direction = "wide", idvar=c("Code", "Cond"), timevar="X")