【问题标题】:How to use gather() function for multiple value arguments in R如何在 R 中对多个值参数使用 collect() 函数
【发布时间】:2019-06-01 11:11:12
【问题描述】:

我是 tidyverse 数据操作的新手,我正在使用 tidyr 包中的 gather() 函数将我的数据从宽格式更改为长格式。
我有以下data 数据框:

id <- 1:10
stim_1_ACC <- 0.5:10
stim_2_ACC <- 10:19
stim_1_RT <- 0.4:10
stim_2_RT <- 15:24
data <- data.frame(id,stim_1_ACC,stim_2_ACC,stim_1_RT,stim_2_RT)

我将为stim 设置一列,其中stim1stim2 作为值,两列ACCRT 作为数值变量。
使用gather() 函数,我只能选择一个value 参数,因此只需为一个变量执行我想要的操作。

data %>%
  gather(key = "Stimuli", value = "ACC", 2:5)

我通过多个步骤、拆分然后绑定数据框列来实现我的目标,但我正在寻找一种更整洁的方法。最终结果会是这样的:

   id   stim  ACC  RT
1   1 stim_1  1.5 900
2   2 stim_1  2.5 901
3   3 stim_1  3.5 902
4   4 stim_1  4.5 903
5   5 stim_1  5.5 904
6   6 stim_2  6.5 905
7   7 stim_2  7.5 906
8   8 stim_2  8.5 907
9   9 stim_2  9.5 908
10 10 stim_2 10.5 909

谢谢!

【问题讨论】:

    标签: r dataframe tidyr


    【解决方案1】:

    可能,收集后你需要使用extract/separate"stim..""RT"/"ACC"组件分开,然后使用spread

    library(dplyr)
    library(tidyr)
    
    data %>%
      gather(key, value, -id) %>%
      extract(key, into = c("stim", "temp"), regex = "(stim_\\d+)_(.*)") %>%
      spread(temp, value)
    

    【讨论】:

    • 完美运行...你能解释一下regex= 的论点吗?或者你能推荐一些文档吗?
    • @FilippoGambarota regex 用于告诉我们如何根据捕获组分隔列。在这种情况下,因为我们想要分成两列,所以我们有两个捕获组,一个具有stim_\\d+ 部分,字符串的其余部分作为第二列。您可以在?extract 阅读更多相关信息。
    【解决方案2】:

    这是separate 的一个选项,通过在字符元素之前的“_”处拆分,将“key”列拆分为“stim”和“temp”

    library(tidyverse)
    data %>% 
       gather(key, value, -id) %>% 
       separate(key, into = c("stim", "temp"), sep="(_)(?=[A-Z])") %>%
       spread(temp, value)
    

    【讨论】:

      猜你喜欢
      • 2012-01-05
      • 2014-01-14
      • 2013-07-15
      • 2014-12-14
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多