【问题标题】:dcast issue on dataframe consisting two columns包含两列的数据帧上的 dcast 问题
【发布时间】:2019-12-19 03:26:07
【问题描述】:

我有一个包含两列的数据框,并尝试将其转换为两种宽格式,如下所示。但是,我无法找出仅包含数字列和非数字列的数据框。

library(tidyverse)
library(reshape2)

sample_frame<-data.frame(id=c("x","x","y","y","z","z"),value=c(1,2,3,4,5,6))

desired_output<-cbind(x=filter(sample_frame,id=="x")$value,
                       y=filter(sample_frame,id=="y")$value,
                      z=filter(sample_frame,id=="z")$value)
sample_frame
desired_output

desired_output<-dcast(sample_frame,id~.,value.var="value")
desired_output

> sample_frame
  id value
1  x     1
2  x     2
3  y     3
4  y     4
5  z     5
6  z     6
> desired_output
     x y z
[1,] 1 3 5
[2,] 2 4 6
> 
> desired_output<-dcast(sample_frame,id~.,value.var="value")
Aggregation function missing: defaulting to length
> desired_output
  id .
1  x 2
2  y 2
3  z 2

如上所示,使用 dcast 给了我聚合。

【问题讨论】:

  • @thelatemail 添加了包裹信息

标签: r dcast


【解决方案1】:

在左侧使用 id 中的序列号。我们使用 1:2,因为每个 id 跨越两行。

dcast(1:2 ~ id, data = sample_frame)[-1]
##   x y z
## 1 1 3 5
## 2 2 4 6

如果您不知道每个 id 跨越多少行,或者行不相邻,或者如果不是所有 id 跨越相同数量的行,则使用此生成左侧。

s <- with(sample_frame, ave(value, id, FUN = seq_along))
dcast(s ~ id, data = sample_frame)[-1]

如果可以使用 data.table,请参阅下面的 cmets 以了解 s 的替代方案。

基础溶液

仅使用基数 R 的解决方案如下,其中 s 来自上方。

xtabs(value ~ s + id, sample_frame)

给出以下 xtabs 对象:

   id
s   x y z
  1 1 3 5
  2 2 4 6

【讨论】:

  • 在这种情况下,我们需要预先知道结果表将有 2 行。
  • 我们不知道这是个问题,但以防万一我添加了代码来展示如何处理它。
  • 您是否也可以考虑:dcast(rowid(id) ~ id, data = sample_frame)[-1]?只是想知道
  • @Ben,问题是使用 reshape2 而不是 data.table 但如果可以接受切换到 data.table 那就行了。
【解决方案2】:

tidyverse 中,您可以为每个id 创建一个唯一的行号并获取宽格式数据。

library(dplyr)

sample_frame %>%
   group_by(id) %>%
   mutate(row = row_number()) %>%
   tidyr::pivot_wider(names_from = id, values_from = value) %>%
   select(-row)

# A tibble: 2 x 3
#      x     y     z
#   <dbl> <dbl> <dbl>
#1     1     3     5
#2     2     4     6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多