简体   繁体   English

根据标志从不同列中的另一个字符串替换一列中的字符串

[英]Replace String in one column from another string in different column based on a flag

Let's assume I have a dataset like this one:假设我有这样一个数据集:

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"))

Now, based on the flag, I'd like to obtain the replacement in the "Name" column of the string in the substitution one, In the end the dataframe should look like this:现在,基于标志,我想在替换字符串的“名称”列中获取替换,最后 dataframe 应该如下所示:

final <- data.frame(Name=c("hello1_World","world","HELLO_world1"))

I've tried with something like this:我试过这样的事情:

index <- df1$Flag == "Yes"
df1$Name[index] <- gsub(df1$Generic[index],df1$Substitution[index])

Maybe it should be done in a new column (also acceptable)也许应该在一个新的专栏中完成(也可以接受)

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

In base R:在基地 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.

相关问题 将一列中的字符串替换为另一列 - Replace string in one column by another column R - 如果列包含来自向量的字符串,则 append 标志到另一列 - R - If column contains a string from vector, append flag into another column 替换一个字符串并用另一个创建一列 - Replace one string and create a column with another R:根据另一列中检测到的字符串从一列中提取数据 - R: extract data from one column based on string detected in another 如何从另一列中的另一个字符串的末尾“减去”出现在一个数据框列中的字符串 - How to “subtract” string appearing in one dataframe column from the end of another string in a different column 根据R中另一列的部分字符串值替换一列中的空白值 - Replace blank values in one column based on partial string values of another in R 根据另一列中的过去值在一列中标记一行 - Flag a row in one column based on past value in another column 在 R 中将字符串从一列提取到另一列 - Extracting a string from one column into another in R 根据条件使用其名称作为字符串替换一列中的值 - Replace values in one column based on condition using its name as a string 如何将具有不同字符串的列替换为一个字符串R? - how to replace a column with different strings to one string R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM