我的数据如下。
Item.Nbr accuracy_level freq
1 82078-002 Worst 1
2 82078-007 Bad 1
3 82078-007 Worst 44
4 82078-007 <NA> 11
5 82078-007 Good 7
我想将accuracy_level列转换为行,如下所示
Item.Nbr Worst Bad <NA> Good
1 82078-002 1 0 0 0
2 82078-007 44 1 11 7
我不确切地知道列accuracy_level
答案 0 :(得分:1)
您可以使用 reshape2 包。
library(reshape2)
dcast(df, Item.Nbr ~ accuracy_level, fill = 0)
# Item.Nbr Bad Good <NA> Worst
# 1 82078-002 0 0 0 1
# 2 82078-007 1 7 11 44
数据:强>
df <- structure(list(Item.Nbr = structure(c(1L, 2L, 2L, 2L, 2L), .Label = c("82078-002",
"82078-007"), class = "factor"), accuracy_level = structure(c(4L,
1L, 4L, 3L, 2L), .Label = c("Bad", "Good", "<NA>", "Worst"), class = "factor"),
freq = c(1L, 1L, 44L, 11L, 7L)), .Names = c("Item.Nbr", "accuracy_level",
"freq"), class = "data.frame", row.names = c("1", "2", "3", "4",
"5"))
答案 1 :(得分:1)
tidyr
的解决方案:
df <- read.table(header = T, text = "Item.Nbr accuracy_level freq
1 82078-002 Worst 1
2 82078-007 Bad 1
3 82078-007 Worst 44
4 82078-007 <NA> 11
5 82078-007 Good 7")
library(tidyr)
df %>% spread(accuracy_level, freq, fill = 0)
#> Item.Nbr <NA> Bad Good Worst
#> 1 82078-002 0 0 0 1
#> 2 82078-007 11 1 7 44
答案 2 :(得分:0)
使用xtabs
xtabs(freq ~ Item.Nbr + accuracy_level, df)
# accuracy_level
#Item.Nbr Bad Good <NA> Worst
# 82078-002 0 0 0 1
# 82078-007 1 7 11 44
reshape
来自base R
res <- reshape(df, idvar='Item.Nbr', timevar='accuracy_level', direction='wide')
res[is.na(res)] <- 0
res