简体   繁体   English

如何在 R 中将多个列合并为一个具有不同名称的列

[英]How to combine multiple columns into one with a different name in R

I am trying to group 18 columns into one.我正在尝试将 18 列组合为一列。 As given in the image below.如下图所示。

My data looks like this我的数据看起来像这样

Data数据

I want my Output to look something like this: (Subject and TGroup are ordered/named randomly)我希望我的 Output 看起来像这样:(主题和 TGroup 是随机排序/命名的)

Subject   TGroup      A
 1        positive    0       
 2        neutral     1 
 3        negative    1   
 4        positive    0     

I pivot the data into a long format, but we can just extract the first part of the name and put all values into one column using names_pattern .我将 pivot 数据转换为长格式,但我们可以只提取名称的第一部分,然后使用names_pattern将所有值放入一列。 Is this kind of what you are looking for?这是你要找的吗? I'm a little unclear on the desired output.我对所需的 output 有点不清楚。

library(tidyverse)

df %>%
  pivot_longer(-c(Subject, TGroup),
               names_to = c('.value'),
               names_pattern = '(.*?)_.*')

Output Output

   Subject TGroup       A
     <dbl> <chr>    <dbl>
 1       1 positive     0
 2       1 positive     0
 3       1 positive     1
 4       2 positive     1
 5       2 positive     1
 6       2 positive     1
 7       3 positive     1
 8       3 positive     0
 9       3 positive     1
10       4 positive     1
11       4 positive     1
12       4 positive     0

Data数据

df <- structure(
  list(
    Subject = c(1, 2, 3, 4),
    TGroup = c("positive", "positive", "positive", "positive"),
    A_1 = c(0, 1, 1, 1),
    A_2 = c(0, 1, 0, 1),
    A_3 = c(1, 1, 1, 0)
  ),
  class = "data.frame",
  row.names = c(NA,-4L)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM