提取部分匹配的元素很简单.
# List of longer names
long_names <- c("apple_pie", "banana_split", "cherry_pie", "lemon_meringue", "blueberry_muffin")
# Partial match pattern
partial_match <- "pie"
# Find the index of the first match
match_index <- grep(partial_match, long_names)
# Extract the corresponding shorter name
short_name <- long_names[match_index]
# Print the result
print(short_name)
输出
[1] "apple_pie" "cherry_pie"
有没有办法用一个更长的查询,用一个较短的名字列表来做类似的事情呢?我想出的最好的是以下几点.
# List of shorter names
short_names <- c("apple", "banana", "cherry", "lemon", "blueberry")
# Longer name (query)
long_name <- "cherry_pie"
# Initialize an empty vector to store partial matches
partial_match <- c()
# Iterate over each short name
for (i in 1:length(short_names)) {
# Check if the short name is a partial match in the long name
if (grepl(short_names[i], long_name)) {
# If it is, add it to the 输出 vector
partial_match <- c(partial_match, short_names[i])
}
}
# Print the partial matches
print(partial_match)
输出
[1] "cherry"
有没有更好的办法?