R 如何变异列名因后缀不同的列?

R 如何变异列名因后缀不同的列?,r,dplyr,R,Dplyr,在这样的数据集中 data_frame(a=letters, a_1=letters, b=letters, b_1=letters) 我想将共享类似“根”的列连接起来,即a与a_1和b与b_1。输出应该如下所示 # A tibble: 26 x 2 a b <chr> <chr> 1 a a a a 2 b b b b 3 c c c c 4 d d d d 5 e e e e 6 f

在这样的数据集中

data_frame(a=letters, a_1=letters, b=letters, b_1=letters)
我想将共享类似“根”的列连接起来,即
a
a_1
b
b_1
。输出应该如下所示

# A tibble: 26 x 2
       a     b
   <chr> <chr>
 1   a a   a a
 2   b b   b b
 3   c c   c c
 4   d d   d d
 5   e e   e e
 6   f f   f f
 7   g g   g g
 8   h h   h h
 9   i i   i i
10   j j   j j
# ... with 16 more rows
#一个tible:26 x 2
a b
a
2b
3C
四维
5 e e
6英尺
7克
8小时
9我
10 j
# ... 还有16行

这里有一种方法

ind <- sub('_.*', '', names(df))
as.data.frame(sapply(unique(ind), function(i) do.call(paste, df[i == ind])))
#     a   b
#1  a a a a
#2  b b b b
#3  c c c c
#4  d d d d
#5  e e e e
#6  f f f f
#7  g g g g
#8  h h h h

ind如果您正在寻找tidyverse方法,您可以使用
tidyr::unite\uu

library(tidyr)

# get a list column name groups
cols <- split(names(df), sub("_.*", "", names(df)))

# loop through list and unite columns
for(x in names(cols)) {
  df <- unite_(df, x, cols[[x]], sep = " ")
}
library(tidyr)
#获取一个列名称组列表
科尔斯