[英]Replace String in one column from another string in different column based on a flag
假設我有這樣一個數據集:
df1 = data.frame(Name=c("<HELLO>_World","World","HELLO_<WORLD>"),
Generic=c("<HELLO>","<HELLO>","<WORLD>"),
Substitution = c("hello1","world","world1"),
Flag = c("Yes","No","Yes"))
現在,基於標志,我想在替換字符串的“名稱”列中獲取替換,最后 dataframe 應該如下所示:
final <- data.frame(Name=c("hello1_World","world","HELLO_world1"))
我試過這樣的事情:
index <- df1$Flag == "Yes"
df1$Name[index] <- gsub(df1$Generic[index],df1$Substitution[index])
也許應該在一個新的專欄中完成(也可以接受)
library(tidyverse)
df1 %>%
mutate(new_name = ifelse(
Flag == "Yes",
unlist(purrr::pmap(list(x = Generic, y = Substitution, z = Name),
~ gsub(..1, ..2, ..3))),
Name))
# Name Generic Substitution Flag new_name
# 1: <HELLO>_World <HELLO> hello1 Yes hello1_World
# 2: World <HELLO> world No World
# 3: HELLO_<WORLD> <WORLD> world1 Yes HELLO_world1
在基地 R 中:
df1$result <- Map(function(flag, str, replace, sub) {
if(flag == 'No') return(str)
else gsub(sub, replace, str, fixed = TRUE)
}, flag = df1$Flag, str = df1$Name, replace = df1$Substitution, sub = df1$Generic)
df1
#> Name Generic Substitution Flag result
#> 1 <HELLO>_World <HELLO> hello1 Yes hello1_World
#> 2 World <HELLO> world No World
#> 3 HELLO_<WORLD> <WORLD> world1 Yes HELLO_world1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.