我是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
,我将有一个列,其中stim1
和stim2
作为值,而两个列ACC
和RT
作为数值变量。
使用gather()
函数,我只能选择一个value
参数,因此只对一个变量做我想做的事情。
data %>%
gather(key = "Stimuli", value = "ACC", 2:5)
我通过多个步骤达到我的目标,拆分并绑定dataframe列,但我正在寻找一种更整洁的方法。最终结果如下:
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
谢谢!
发布于 2019-06-01 03:18:44
可能,在收集之后,您将需要使用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)
发布于 2019-06-01 07:28:26
下面是一个使用separate
的选项,通过在字符元素之前的'_‘处拆分’_‘将'key’列拆分为'stim‘和'temp’。
library(tidyverse)
data %>%
gather(key, value, -id) %>%
separate(key, into = c("stim", "temp"), sep="(_)(?=[A-Z])") %>%
spread(temp, value)
https://stackoverflow.com/questions/56406188
复制相似问题