首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tidyr::扩展导致多行

tidyr::扩展导致多行
EN

Stack Overflow用户
提问于 2018-08-07 02:44:43
回答 2查看 186关注 0票数 1

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

我有一个如下结构的df:

代码语言:javascript
复制
    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

使用以下代码:

代码语言:javascript
复制
  dftest <- bd_teste %>%
  select(-UndesiredIndex) %>%
  spread(DesiredIndex, Result)

我所期望的结果如下:

代码语言:javascript
复制
DesiredIndex    A   B
A   50,32   50,33
B   7,34    7,35

尽管如此,我还是得到了以下结果:

代码语言:javascript
复制
    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的新手,我一直在努力解决这个问题,但没有成功。提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-07 03:46:00

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

代码语言:javascript
复制
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 

数据

代码语言:javascript
复制
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")
)
票数 1
EN

Stack Overflow用户

发布于 2018-08-07 10:08:36

更短,但在理论上更具回旋余地。

数据

(感谢@akrun!)

代码语言:javascript
复制
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")
)

这是连接行的一种很好的技术。

代码语言:javascript
复制
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创建于2018-08-06 (v0.2.0)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51713846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档