问题描述
我有以下数据框
df<-read.table(text="Study.ID Studlab Cohort.size No.DTA No.TAA Operative.mortality.DTA Operative.mortality.TAA
30 Coselli2016 3309 0 3309 NA 249
42 Estrera2015 1896 646 1273 79 223
212 Youssef2015 62 NA 62 NA 14
203 Weiss2012 240 72 168 2 7
189 Tabayashi2010 102 4 98 0 6", sep="", header=T)
,但我需要它看起来像这样
but I need it to look like this
基本上重新塑形并添加2个新列 Studlab.R和组。 Studlab.R是 Studlab和 group列的组合。
我发现了用于重塑的不同链接(例如,但我仍在为此而苦苦挣扎
Basically reshaping and adding 2 new columns "Studlab.R and group" . Studlab.R is a combination of 'Studlab" and "group" columns.I found different links for reshaping (eg here but I am still struggling with this
任何建议都将不胜感激。
Any advice will greatly appreciated.
推荐答案
我将使用 tidyverse gather()
/ code>包,并分3个步骤执行此操作,首先收集NO.XXX,然后在步骤3中将Operative.XXX合并在一起后,在其中添加带有变异的列'Studlab.R'
I would use gather()
from tidyverse
package and do this in 3 steps first gather the NO.XXX and than the Operative.XXX after taht join it together in Step 3 add the column 'Studlab.R' with mutate
library(tidyverse)
#1
df2 <- df %>%
select(-starts_with("Operative")) %>%
gather(key = "group", value = "No.DTR.TAA", No.DTA, No.TAA) %>%
mutate(group = str_remove(group, "No\\."))
#2
df_tmp <- df %>%
select(-starts_with("No")) %>%
gather(key = "group", value = "Operative.mortality.DTA.TAA", Operative.mortality.DTA, Operative.mortality.TAA) %>%
mutate(group = str_remove(group, "Operative\\.mortality\\."))
#3
df2 <- df2 %>%
full_join(df_tmp) %>%
mutate(Studlab.R = paste0(Studlab, " (", group, ")"))
这篇关于我想将当前数据框(带有一些空单元格)重塑为另一个数据框并创建新列(连接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!