如果第一个列表中的元素与第二个列表中的元素相同,则替换为第三个列表中的元素

问题描述 投票:0回答:1

我有三份清单

示例数据

data <- list("A-B", "C-D", "E-F", "G-H", "I-J")
data_to_replace  <- list("A-B", "C-D")
replacement <- list("B-A", "D-C")
## Note: The length(data_to_replace)  and length(replacement ) are always equal. Which may range from 1 to 200

这只是一个最小的例子。这三个我有几个,每个列表上的数量各不相同

预期结果

data_new <- list("B-A", "D-C", "E-F", "G-H", "I-J")

我尝试过的事情

## function that reverses a string by words
reverse_words <- function(string) {
  ## split string by blank spaces
  string_split <- strsplit(as.character(string), split="-")
  ## How many split terms?
  string_length <- length(string_split[[1]])
  ## decide what to do
  if (string_length == 1) {
    ## one word (do nothing)
    reversed_string <- string_split[[1]]
  } else {
    ## more than one word (collapse them)
    reversed_split <- string_split[[1]][string_length:1]
    reversed_string <- paste(reversed_split, collapse="-")
  }
  ## output
  return(reversed_string)
} 

## Replacemnt
replacement <- lapply(data_to_replace, reverse_words)
data_new <- rapply(data, function(x) {
  replace(x, x == data_to_replace, replacement) ## This last line did not work
})
r string list
1个回答
1
投票

将您的输入转换为向量,然后您可以执行以下操作:

## direct replacement
data[data %in% data_to_replace] = replacement[match(data, data_to_replace)]

## or with `ifelse` if you want to save it as a new name 
## and keep `data` unmodified
ifelse(data %in% data_to_replace, replacement[match(data, data_to_replace)], data)
© www.soinside.com 2019 - 2024. All rights reserved.