[英]How to combine multiple columns into one with a different name in R
我正在嘗試將 18 列組合為一列。 如下圖所示。
我的數據看起來像這樣
我希望我的 Output 看起來像這樣:(主題和 TGroup 是隨機排序/命名的)
Subject TGroup A
1 positive 0
2 neutral 1
3 negative 1
4 positive 0
我將 pivot 數據轉換為長格式,但我們可以只提取名稱的第一部分,然后使用names_pattern
將所有值放入一列。 這是你要找的嗎? 我對所需的 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
數據
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.