简体   繁体   中英

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

I am trying to group 18 columns into one. 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)

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 . Is this kind of what you are looking for? I'm a little unclear on the desired output.

library(tidyverse)

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

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)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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