R pivot_longer 根据列名的结尾组合列 [英] R pivot_longer combining columns based on the end of column names

查看:27
本文介绍了R pivot_longer 根据列名的结尾组合列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个列的数据框,其名称具有不同的长度和结构(因此不确定如何使用正则表达式捕获它们).每列以 .t1.t3

I have a dataframe with multiple columns with names of various lengths and structures (so not sure how to capture them with a regex). Each column ends either with .t1 or .t3

我想将基于没有 t1/t3 的名称的列与基于该后缀的 Time 附加列组合在一起.

I want to combine columns based on names without the t1/t3, with an additional column of Time based on that suffix.

例如,一个数据框,例如:

So, for example, a dataframe such as:

df<-data.frame("Subject"= c(1:10),
"intercept.freq.acc.t1" = c(1:10),
"intercept.freq.acc.t3" = c(1:10),
"freq.rt.t1" = c(1:10), 
"freq.rt.t3" = c(1:10),
"vowel.con.acc.t1" = c(1:10),
"vowel.con.acc.t3" = c(1:10))

我想把它变成

df<-data.frame("Subject"= rep(1:10,2),
"Time" = rep(c('t1','t3'), each = 10),
"intercept.freq.acc" = rep(1:10, 2),
"freq.rt" = rep(1:10,2), 
"vowel.con.acc" = rep(1:10, 2))

我该怎么做?

推荐答案

您可以使用:

tidyr::pivot_longer(df, 
             cols = -Subject, 
             names_to = c('.value', 'Time'), 
             names_pattern = '(.*)\\.(t\\d+)')

#   Subject Time  intercept.freq.acc freq.rt vowel.con.acc
#     <int> <chr>              <int>   <int>         <int>
# 1       1 t1                     1       1             1
# 2       1 t3                     1       1             1
# 3       2 t1                     2       2             2
# 4       2 t3                     2       2             2
# 5       3 t1                     3       3             3
# 6       3 t3                     3       3             3
# 7       4 t1                     4       4             4
# 8       4 t3                     4       4             4
# 9       5 t1                     5       5             5
#10       5 t3                     5       5             5
#11       6 t1                     6       6             6
#12       6 t3                     6       6             6
#13       7 t1                     7       7             7
#14       7 t3                     7       7             7
#15       8 t1                     8       8             8
#16       8 t3                     8       8             8
#17       9 t1                     9       9             9
#18       9 t3                     9       9             9
#19      10 t1                    10      10            10
#20      10 t3                    10      10            10

这篇关于R pivot_longer 根据列名的结尾组合列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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