【发布时间】:2020-08-28 13:24:54
【问题描述】:
我正在尝试使用之前提供的相同代码 link 将我的数据重塑为长格式而不是宽格式,但是即使经过多次尝试修改 names_pattern = "(.*)_(pre|post.*)", 也无法正常工作
我的数据样本是
data1<-read.table(text="
Serial_ID pre_EDV pre_ESV pre_LVEF post_EDV post_ESV post_LVEF
1 76.2 32.9 56.8 86.3 36.6 57.6
2 65.4 35.9 45.1 60.1 26.1 56.7
3 64.4 35.1 45.5 72.5 41.1 43.3
4 50 13.9 72.1 46.4 18.4 60.4
5 89.6 32 64.3 70.9 19.3 72.8
6 62 20.6 66.7 55.9 17.8 68.2
7 91.2 37.7 58.6 61.9 23.8 61.6
8 62 24 61.3 69.3 34.9 49.6
9 104.1 22.7 78.8 38.6 11.5 70.1
10 90.6 31.2 65.6 48 16.1 66.4", sep="", header=T)
我想将我的数据重塑为
- 将相同的列标题放在彼此下方,例如下方的 post_EDV pre_EDV
- 创建新列 Pre vs. post
- 修复列标题(将“pre_”和“post_”删除为仅“EDV”(如下面的屏幕截图所示))。
这是使用的代码:
library(dplyr);library(tidyr);library(stringr)
out <- data %>% pivot_longer(cols = -Serial_ID,
names_to = c(".value", "prevspost"),
names_pattern = "(.*)_(pre|post.*)",
names_sep="_") #%>% as.data.frame
我也尝试了names_prefix = c("pre_","post_") 而不是names_pattern = "(.*)_(pre|post.*)",,但它不起作用。
任何建议将不胜感激。
【问题讨论】:
-
请提供一个可重现的问题,方法是添加一个最小数据作为对象,或者作为数据框,例如
data <- data.frame(...)其中 ... 是变量和值或dput(head(data, n = 20))