gpt4 book ai didi

r - 如何改变列名因后缀而不同的列?

转载 作者:行者123 更新时间:2023-12-05 00:50:55 25 4
gpt4 key购买 nike

在像这样的数据集中

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

最佳答案

如果您正在寻找一种 tidyverse 方法,您可以使用 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 = " ")
}

关于r - 如何改变列名因后缀而不同的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45098633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com