我正在尝试将数据框从一种格式转换为我一直盯着的另一种格式:
>dfst
cat1 cat2 cat3
a x 1
b x 2
c x 3
a y 9
b y 8
c y 7
我正在努力做到:
x y
a 1 9
b 2 8
c 3 7
当前我的代码如下:
#make the new df
df <- data.frame(matrix(ncol = length(unique(df$cat1)),
nrow = length(unique(df$cat2))))
row.names(df) <- unique(df$cat2)
colnames(df) <- unique(df$cat1)
f <- function(x, out= df){
val.row <- x[[1]]
val.col <- x[[3]]
out[val.row, val.col] <- x[[2]]
}
apply(dfst, 1, f, out = df)
打印语句为我提供了val.row和val.col的正确值,它甚至可以找到我用print(out [val.row,val.col])手动加载的值,但不会加载x [[ 2]]。
据我所知out["a", "x"] <- dfst[1, 3]
也有效。
有什么建议吗?
答案 0 :(得分:4)
您可以从基数R使用reshape
reshape(dfst,timevar = "cat2",idvar = "cat1",dir="wide")
cat1 cat3.x cat3.y
1 a 1 9
2 b 2 8
3 c 3 7
或者您可以这样做:
data.table::dcast(dfst,cat1~cat2)
答案 1 :(得分:3)
另一个选择是xtabs
中的base R
xtabs(cat3~ cat1 + cat2, dfst)
# cat2
#cat1 x y
# a 1 9
# b 2 8
# c 3 7
dfst <- structure(list(cat1 = c("a", "b", "c", "a", "b", "c"), cat2 = c("x",
"x", "x", "y", "y", "y"), cat3 = c(1L, 2L, 3L, 9L, 8L, 7L)),
class = "data.frame", row.names = c(NA,
-6L))