R 如何将mutate和gsub结合使用

R 如何将mutate和gsub结合使用,r,R,我正在使用mutate和paste和gsub来编写代码。这是一种我可以一块一块写的方式吗 我的代码是: PMath <- PMath %>% mutate(MathALL = paste(MathMED, MathPR, MathACNOTH, sep = "; ")) PMath$MathALL <- gsub(pattern = "( ; )|(; $)|\\.",replacement = "", PMath$

我正在使用
mutate
paste
gsub
来编写代码。这是一种我可以一块一块写的方式吗

我的代码是:

PMath <- PMath %>% mutate(MathALL = paste(MathMED, MathPR, MathACNOTH, sep = "; "))
PMath$MathALL <- gsub(pattern = "( ; )|(;  $)|\\.",replacement = "", PMath$MathALL, fixed = FALSE)
PMath%变异(MathALL=paste(MathMED,MathPR,MathACNOTH,sep=“;”))

PMath$MathALL它是赋值运算符(
%
将是

library(dplyr)
PMath %>%
     mutate(MathALL = paste(MathMED, MathPR, MathACNOTH, sep = "; ") %>%
               gsub(pattern = "( ; )|(;  $)|\\.",
                replacement = "", ., fixed = FALSE))

有点奇怪的是,OP正在创建一个delimier(
),然后删除它

在tidyverse中,也可以使用
unite

 library(tidyr)
 PMath %>%
        unite(MathAll, MathMED, MathPR, MathACNOTH, sep="; ", na.rm = TRUE)

赋值应该是
=
内部
变异
而不是
值中有一些“”和NA,因此我必须用
@Stataq删除空的赋值。代码是正确的。例如
头(mtcars)%%>%unite(amgearcarb,am,gear,carb,sep=“;”,NA.rm=TRUE)%%>%pull(amgearb)#[1]“1;4;4”“1;4”“1”“0;3;1”“0;3;2”“0;3;1”
@Stataq这里,是我得到的输出
df%>%unite(tst5,tst1,tst2,tst3,tst4,sep=“;”,na.rm=TRUE,remove=FALSE)%%>%pull(tst5)[1]“保持;1支架放置”“保持;治疗药物:10 Ondensetron,12-氯拉嗪”[3]”持有;治疗药物:10 Ondensetron,12 Prochloroperazine“持有;不满意;治疗药物:14吗啡”[5]“持有;治疗药物….
@Stataq在您发布的示例中,即使有很多NAs,我也没有收到这样的病例。我在更改后使用了
packageVersion(“tidyr”)#[1]“1.1.2”
对娜来说,一切都是我想要的。
library(dplyr)
PMath %>%
     mutate(MathALL = paste(MathMED, MathPR, MathACNOTH, sep = "; ") %>%
               gsub(pattern = "( ; )|(;  $)|\\.",
                replacement = "", ., fixed = FALSE))
 library(tidyr)
 PMath %>%
        unite(MathAll, MathMED, MathPR, MathACNOTH, sep="; ", na.rm = TRUE)