操纵R中的数据框

时间:2015-07-09 07:13:55

标签: r dataframe reshape

我有一个看起来像这样的表:

id  pop  fre
A:1 sh   0.6
A:1 mi   0.2
A:2 sh   0.9
A:3 mi   0.5

我想要的是创建一个新表,第二列(pop)作为列名和值(id)列而不重复。 (fre)列的相应值用于填充表。例如,上表可能如下所示:

id    sh    mi
A:1   0.6  0.2
A:2   0.9  NA
A:3   NA   0.5

我尝试在R中使用reshape函数,但是我一直收到有关数据框列的错误。我感谢任何可能有用的想法。

1 个答案:

答案 0 :(得分:2)

您可以尝试dcast

library(reshape2)
dcast(df1, id~pop, value.var='fre')

或者

library(tidyr)
spread(df1, pop, fre)

或使用base R(基于显示的示例)

 xtabs(fre~id+pop, df1)

reshape

中的base R
 reshape(df1, idvar='id', timevar='pop', direction='wide')

数据

df1 <- structure(list(id = c("A:1", "A:1", "A:2", "A:3"), pop = c("sh", 
"mi", "sh", "mi"), fre = c(0.6, 0.2, 0.9, 0.5)), .Names = c("id", 
"pop", "fre"), class = "data.frame", row.names = c(NA, -4L))

df1$pop <- factor(df1$pop, levels=unique(df1$pop))
相关问题