1

我如何重新安排一张桌子。我有以下数据框:

        1_3         red     0.988
        1_3         blue    0.020
        2_5         red     0.110
        2_5         green   0.299
        4_6         red     0.349
        4_6         blue    0.750

现在,我想重新排列此表,使文件列表位于 x 轴上,颜色位于 y 轴上,如下表所示。

             1_3        2_5     4_6
red         0.988       0.110       0.349
blue        0.020       0.000       0.750
green       0.000       0.299       0.000

我尝试使用 dcast 函数,但它需要一个 FUN 条目,否则它默认为长度,除非我将函数应用于列。有些东西告诉我我错过了一些关于 dcast 的东西。有什么想法吗?

这就是我应用于表格的内容。以下行生成有关 FUN 的错误。如果我删除它,dcast 会说我需要一个函数。

  dcast(color ~ file, value.var = "freq", fill = 0, FUN = NULL)
4

1 回答 1

1

没有FUN争论,这是fun.aggregate

library(reshape2)
dcast(df1, color ~ file, value.var = "freq", fill = 0, fun.aggregate = NULL)
#. color   1_3   2_5   4_6
#1  blue 0.020 0.000 0.750
#2 green 0.000 0.299 0.000
#3   red 0.988 0.110 0.349

数据

df1 <- structure(list(file = c("1_3", "1_3", "2_5", "2_5", "4_6", "4_6"
), color = c("red", "blue", "red", "green", "red", "blue"), freq = c(0.988, 
0.02, 0.11, 0.299, 0.349, 0.75)), class = "data.frame", row.names = c(NA, 
-6L))
于 2019-10-02T18:04:28.087 回答