R如何在扩展数据帧时在dcast中使用fun.aggregate来保持离散值?

R how to use fun.aggregate in dcast to keep discrete values when widening dataframe?

我一直在尝试使用 reshape2 中的 dcast() 函数来扩大 R 中的大型数据框。但是,我不确定聚合函数要使用什么,fun.aggregate dcast 需要,因为我想保留 value.var 的离散值,而 dcast 坚持强制将 length 作为默认值,使每个值都是二分法。为了说明,我的数据如下所示:

x <- c("a", "b", "c")
y <- c("d", "e", "f")
num <- c(10, 20, 21)
data <- data.frame(cbind(x,y,num))

x y num
a d  10
b e  20
c f  21

输入m <- dcast(data, x ~ y, value.var = "num")后,dcastreturns如下DF:

  d  e  f
a 1  0  0
b 0  1  0
c 0  0  1

但是,我希望它看起来像这样:

  d  e  f
a 10 0  0
b 0  20 0
c 0  0  21

我做错了什么?

您也可以切换到 tidyr

library(tidyverse)

x <- c("a", "b", "c")
y <- c("d", "e", "f")
num <- c(10, 20, 21)

df <- tibble(x, y, num)

df %>% 
  spread(y,  num, fill = 0)

输出为:

# A tibble: 3 x 4
  x         d     e     f
  <chr> <dbl> <dbl> <dbl>
1 a        10     0     0
2 b         0    20     0
3 c         0     0    21