我想改变这个
Person Error_Type
[1,] Name_1 Type_A
[2,] Name_2 Type_B
[3,] Name_1 Type_A
[4,] Name_3 Type_C
[5,] Name_2 Type_C
[6,] Name_1 Type_B
进入这个:
Person Type_A Type_B Type_C
[1,] Name_1 2 1 -
[2,] Name_2 - 1 1
[3,] Name_3 - 0 1
Names_
和Type_
都是字符串
谢谢!
答案 0 :(得分:2)
正如@thelatemail针对给出的示例所指出的那样,table
几乎完全给出了OP在一个函数调用中所请求的内容。
df <- data.frame(Person = c("Name_1","Name_2","Name_1","Name_3","Name_2","Name_1"),
Error_Type = c("Type_A","Type_B","Type_A","Type_C","Type_C","Type_B"),
stringsAsFactors = FALSE)
table(df)
Error_Type
Person Type_A Type_B Type_C
Name_1 2 1 0
Name_2 0 1 1
Name_3 0 0 1
然而,OP已经声明实际数据比给定的例子稍微复杂一些。下面是一个基础R解决方案,应该在更一般的水平上工作。
MakeDf <- function(myDf) {
myCols <- unique(myDf$Error_Type)
z <- split(myDf, myDf$Person)
lenR <- length(z)
newDf <- data.frame(matrix(rep(0, lenR*length(myCols)), nrow = lenR))
colnames(newDf) <- myCols; rownames(newDf) <- names(z)
for (i in 1:lenR) {
t <- rle(z[[i]]$Error_Type)
newDf[i, t$values] <- t$lengths
}
newDf
}
MakeDf(df)
Type_A Type_B Type_C
Name_1 2 1 0
Name_2 0 1 1
Name_3 0 0 1
答案 1 :(得分:0)
试试这个......(myMat是上面描述的矩阵)
myMat <- data.frame(myMat)
aggregate(myMat, by = list(myMat$Error_Type), FUN = length)
该函数将通过“by”参数中列出的内容按指定的函数聚合第一个参数。