As @thelatemail pointed out for the example given, table
gives almost exactly what the OP requested in one function call.
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
However, the OP has stated that the actual data is a bit more complex than the given example. Below is a base R solution that should work on a more general level.
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
This function takes advantage of split and rle (very similar to table).