我正在尝试将长数据形式转换为 R 中的宽数据形式。例如,我有以下数据框:
a = rep(c("A","B","C","D"),4)
b = rep(c("COL1","COL2","COL3","COL4"),4)
val = 101:116
df = as.data.frame(cbind(a,b,val))
df
我希望看到结果为:
row <- as.list(levels(df$a))
col <- as.list(levels(df$b))
test <- data.frame()
i = 1
for (j in 1:4) {
for(k in 1:4){
test[j,k] = df$val[i]
i = i + 1
}
}
colnames(test) <- c("COL1","COL2","COL3","COL4")
rownames(test) <- c("A","B","C","D")
test
如果您能使用一些方便的功能提出一个优雅的解决方案,将不胜感激。谢谢,卡西姆