R - tidyr - 变异和传播多列 [英] R - tidyr - mutate and spread multiple columns

查看:26
本文介绍了R - tidyr - 变异和传播多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中有以下数据框

I have the following dataframe in R

my_df_test <- data.frame(V1 = c(1,2,1), V2 = c("A","B","A"), V3 = c("S1", "S1", "S2"), V4 = c("x","x","x"), V5 = c("y","y","y"), V6 = c("A", "B", "C"), V7 = c("D","E","F"))

my_df_test
  V1 V2 V3 V4 V5 V6 V7
1  1  A S1  x  y  A  D
2  2  B S1  x  y  B  E
3  1  A S2  x  y  C  F

现在我想检查 V1 和 V2 中值的组合是否在 df 中多次出现.在我的示例中,my_df 第 1 行和第 3 行具有相同的值1 A"和1 A".如果发生这种情况,我需要以下输出:

Now I want to check if the combination of values in V1 and V2, occurs multiple times in the df. In my example my_df lines 1 and 3 have the same values '1 A' and '1 A'. If this happens, I want the following output:

> my_df_test

   V1 V2     V3 V4 V5  V6_S1   V6_S2   V7_S1   V7_S2
 1  1  A S1, S2  x  y      A       C       D       F
 2  2  B     S1  x  y      B      NA       E      NA

所以基本上有两件事发生了变化:

So basically two things have changed:

  • V3 现在包含 df 中所有行的值,其中 V1 和 V2 中的值相同.它们以,"分隔
  • 有新的 V6 &V7 列包含这些列的原始值

其余的列和值应保持不变.

The rest of the columns and values should stay the same.

当只有 1 个类似V6"的列时,我的代码可以正常工作.但是,当有多个时,这不再起作用.

I have code that works when there is only 1 'V6' like column. However when there are multiple this doesn't work anymore.

my_df_test %>%
    group_by(V1, V2) %>%
    mutate(new = paste0("V6_", V3), V3 = toString(V3)) %>%
    spread(new, V6)

所以我的问题是应该如何调整我的代码以改变和传播多列?

So my question is how my code should be adapted to mutate and spread multiple columns?

推荐答案

您可以使用新的 pivot_wider() 而不是 spread()最近的 tidyr 1.0.0 版本.它有一个 values_from 参数,允许您一次指定多个列:

Rather than spread(), you can use the new pivot_wider() that was added in the recent tidyr 1.0.0 release. It has a values_from argument that allows you to specify multiple columns at once:

library(dplyr)
library(tidyr)

my_df_test %>% 
  group_by(V1, V2) %>% 
  mutate(new = V3, V3 = toString(V3)) %>% 
  pivot_wider(
    names_from  = new,
    values_from = c(V6, V7)
  )
#> # A tibble: 2 x 9
#> # Groups:   V1, V2 [4]
#>      V1 V2    V3     V4    V5    V6_S1 V6_S2 V7_S1 V7_S2
#>   <dbl> <fct> <chr>  <fct> <fct> <fct> <fct> <fct> <fct>
#> 1     1 A     S1, S2 x     y     A     C     D     F    
#> 2     2 B     S1     x     y     B     <NA>  E     <NA>

reprex 包 (v0.3.0) 于 2019 年 9 月 18 日创建

Created on 2019-09-18 by the reprex package (v0.3.0)

这篇关于R - tidyr - 变异和传播多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆