如何改变列名称后缀不同的列?

时间:2017-07-14 08:49:20

标签: r dplyr

在像

这样的数据集中
data_frame(a=letters, a_1=letters, b=letters, b_1=letters)

我想连接共享类似“根”的列,即aa_1bb_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

2 个答案:

答案 0 :(得分:4)

如果您正在寻找一种整齐的方法,可以使用tidyr::unite_来实现:

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 = " ")
}

答案 1 :(得分:1)

这是一种方法,

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