R 基于列名将多个列堆叠在一个列中

R 基于列名将多个列堆叠在一个列中,r,dataframe,multiple-columns,reshape2,columnsorting,R,Dataframe,Multiple Columns,Reshape2,Columnsorting,我的数据框架由269个变量的53个观测值组成。 结构与此类似: id w.0 v.0 a.0 w.1 v.1 a.1 1 1 here 7 5 wor 1 7 4 4 are 6 8 ds 5 4 7 7 some 7 2 hey

我的数据框架由269个变量的53个观测值组成。 结构与此类似:

   id            w.0 v.0 a.0         w.1 v.1 a.1            
1   1           here   7   5         wor   1   7         
4   4            are   6   8          ds   5   4        
7   7           some   7   2         hey   3   8           
   id          words  va  ac                     
1   1           here   7   5                  
2   2            are   6   8                  
3   3           some   7   2           
4   4            wor   1   7
5   5             ds   5   4
6   6            hey   3   8 
     id time  words   va   ac
1.1   1    1   here  are  some
4.1   4    1    wor   ds   hey
7.1   7    2      7    6     7
8.1   8    2      1    5     3
10.1 10    3      5    8     2
11.1 11    3      7    4     8
列名上升到w.26、v.26、a.26

我的任务是创建三个主要列:words、va、ac,因此是一个长格式数据框,类似于以下内容:

   id            w.0 v.0 a.0         w.1 v.1 a.1            
1   1           here   7   5         wor   1   7         
4   4            are   6   8          ds   5   4        
7   7           some   7   2         hey   3   8           
   id          words  va  ac                     
1   1           here   7   5                  
2   2            are   6   8                  
3   3           some   7   2           
4   4            wor   1   7
5   5             ds   5   4
6   6            hey   3   8 
     id time  words   va   ac
1.1   1    1   here  are  some
4.1   4    1    wor   ds   hey
7.1   7    2      7    6     7
8.1   8    2      1    5     3
10.1 10    3      5    8     2
11.1 11    3      7    4     8
我使用了以下代码:

df_reshaped <- reshape(subset(df), 
              varying=Map(function(x) paste(c("w","v", "a"), x, sep="."), 
                          c("0","1","2","3","4","5","6","7","8","9","10","11","12","13","14",
                            "14","15","16","17","18","19","20","21","22","23","24","25","26")),
              v.names=c("words","va","ac"),
              idvar= "id",    
              direction="long")

任何帮助都将不胜感激。谢谢。

我们可以再使用
pivot\u

library(dplyr)
library(tidyr)
df1 %>% 
  pivot_longer(cols = -id, names_to = c('.value', 'group'), names_sep="\\.")%>% 
  select(-group) %>% 
  rename_at(-1, ~ c('words', 'va', 'ac'))
数据
df1您可以像这样使用
重塑
重塑(dat,idvar=“id”,variable=2:ncol(dat),direction=“long”,sep=“.”