提取部分匹配的元素很简单.

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

有没有更好的办法?

推荐答案

以R为基数,你可以用regmatches

> regmatches(long_name, gregexpr(paste0(short_names, collapse = "|"), long_name))
[[1]]
[1] "cherry"

R相关问答推荐

按崩溃类别分类的指数

在数据表中呈现数学符号

如何在xyplot中 for each 面板打印R^2

在"gt"表中添加第二个"groupname_col",而不连接列值

制作等距离的线串副本

在rpart. plot或fancyRpartPlot中使用带有下标的希腊字母作为标签?

当我们有多个反斜杠和/特殊字符时使用Gsubing

如何从容器函数中提取conf并添加到ggplot2中?

具有重复元素的维恩图

在多页PDF中以特定布局排列的绘图列表不起作用

ggplot R:X,Y,Z使用固定/等距的X,Y坐标绘制六边形热图

创建在文本字符串中发现两个不同关键字的实例的数据框

如何使用包metaviz更改标签的小数位数?

R中的Desolve:返回的导数数错误

R没有按顺序显示我的有序系数?

通过匹配另一个表(查找表)中的列值来填充数据表,并在另一个变量上进行内插

如何创建直方图与对齐的每月箱?

在直方图中显示两个变量

使用点图调整离散轴比例

R:部分修改矩阵对角线的有效方法