【问题标题】:tidyr::spread resulting in multiple rowstidyr::spread 导致多行
【发布时间】:2018-08-06 18:44:43
【问题描述】:

我遇到了与以下类似的问题,但以下链接中提供的解决方案对我不起作用: tidyr spread does not aggregate data

我的 df 结构如下:

    UndesiredIndex  DesiredIndex    DesiredRows Result
1   x1A x1  A   50,32
2   x1B x2  B   7,34
3   x2A x1  A   50,33
4   x2B x2  B   7,35

使用下面的代码:

  dftest <- bd_teste %>%
  select(-UndesiredIndex) %>%
  spread(DesiredIndex, Result)

我期望得到以下结果:

DesiredIndex    A   B
A   50,32   50,33
B   7,34    7,35

虽然,我不断得到以下结果:

    DesiredIndex    x1  x2
1   A   50.32   NA
2   B   7.34    NA
3   A   NA  50.33
4   B   NA  7.35

PS:有时我用 select(-UndesiredIndex) 强制列 UndesiredIndex,但我不断收到以下消息:

添加缺少的分组变量:UndesiredIndex

堆叠这些行可能很容易,但我是 R 新手,一直在努力解决这个问题,但没有成功。 提前致谢!

【问题讨论】:

  • 试试aggregate(Result~DesiredRows,dat,paste)。首先确保您的列不是因素而是字符
  • 试试df1 %&gt;% select(-UndesiredIndex) %&gt;% group_by(DesiredIndex) %&gt;% mutate(new =LETTERS[row_number()]) %&gt;% ungroup %&gt;% select(-DesiredRows) %&gt;% spread(DesiredIndex, Result)
  • @Onyambu 提前感谢您的帮助,但建议的解决方案返回未找到 dat 参数。我应该用我的 df 的名字填写它吗?
  • @akrun 提前感谢您的帮助,但不幸的是,结果相同。
  • 根据您显示的输入,它给了我预期的输出

标签: r tidyr spread


【解决方案1】:

我们按DesiredIndex分组,创建一个序列列,然后执行spread

library(tidyverse)

df1 %>% 
    select(-UndesiredIndex) %>% 
    group_by(DesiredIndex) %>% 
    mutate(new = LETTERS[row_number()]) %>% 
    ungroup %>%
    select(-DesiredIndex) %>% 
    spread(new, Result)

# A tibble: 2 x 3
#  DesiredRows A     B    
#  <chr>       <chr> <chr>
#1 A           50,32 50,33
#2 B           7,34  7,35 

数据

df1 <- structure(
    list(
        UndesiredIndex = c("x1A", "x1B", "x2A", "x2B"), 
        DesiredIndex = c("x1", "x2", "x1", "x2"), 
        DesiredRows = c("A", "B", "A", "B"), 
        Result = c("50,32", "7,34", "50,33", "7,35")
    ), 
    class = "data.frame", 
    row.names = c("1", "2", "3", "4")
)

【讨论】:

  • 非常感谢@akrun。它在我原来的 df 中不起作用,但在此处输入时确实起作用。
【解决方案2】:

更短,但理论上更迂回。

数据

(感谢@akrun!)

df1 <- structure(
    list(
        UndesiredIndex = c("x1A", "x1B", "x2A", "x2B"), 
        DesiredIndex = c("x1", "x2", "x1", "x2"), 
        DesiredRows = c("A", "B", "A", "B"), 
        Result = c("50,32", "7,34", "50,33", "7,35")
    ), 
    class = "data.frame", 
    row.names = c("1", "2", "3", "4")
)

这是连接行的好方法。

df1 %>% 
  group_by(DesiredRows) %>% 
  summarise(Result = paste(Result, collapse = "|")) %>% #<Concatenate rows
  separate(Result, into = c("A", "B"), sep = "\\|")     #<Separate by '|'

#> # A tibble: 2 x 3
#>   DesiredRows A     B    
#>   <chr>       <chr> <chr>
#> 1 A           50,32 50,33
#> 2 B           7,34  7,35

reprex package (v0.2.0) 于 2018 年 8 月 6 日创建。

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 2019-12-31
    • 1970-01-01
    • 2016-05-24
    • 2016-09-16
    • 2016-03-07
    • 2018-08-19
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多