我有三份清单
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
})
将您的输入转换为向量,然后您可以执行以下操作:
## 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)