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

时间:2019-02-24 17:37:41

标签: r dataframe reshape reshape2

我一直在尝试使用dcast()中的reshape2函数来加宽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")后,dcast返回以下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

我在做什么错了?

1 个答案:

答案 0 :(得分:-1)

您也可以切换到function groupIntoThrees (children) { const output = [] let currentGroup = [] children.forEach((child, index) => { currentGroup.push(child) if (index % 3 === 2) { output.push(currentGroup) currentGroup = [] } }) return output } ... later in render method ... <Carousel className="col-md-7 col-11" indicators="true" controls="false"> {groupIntoThrees(this.props.children).map((group) => ( <Carousel.Item> <h1>first: {group[0]}</h1> <h1>middle: {group[1]}</h1> <h1>last: {group[2]}</h1> </Carousel.Item> )} </Carousel>

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)