我有一个多列数据框中的一列,让我们称其为df1,它由一些文本组成,下面是一些示例行:

"896 European ancestry cases, 2,455 European ancestry controls"
"591 European individuals, 687 European males"
"1,968 African American cases, 3,928 African American controls"

然后我在另一个数据框中有两列,我们称其为df2,如下所示:

"European ancestry cases", "European"
"European ancestry controls", "European"
"European individuals", "European"
"European males", "European"
"African American cases", "African"
"African American controls", "African"

引号实际上并不在那里,我只是用它们来澄清列数.

我想将第df2列的所有实例替换为第df2列的第二列.换句话说,我只想更改df1,但使用df2中的信息,这将返回以下结果:

"896 European, 2,455 European"
"591 European, 687 European"
"1,968 African, 3,928 African"

对于如何在R中实现这一点有什么 idea 吗?

一百零二

推荐答案

你可以试一试

# 1
gsub("(European|African)([^,]+)", "\\1", df1$txt)

# 2
gsub("(?<=European|African)[^,]+", "", df1$txt, perl = TRUE)

# [1] "896 European, 2,455 European"
# [2] "591 European, 687 European"  
# [3] "1,968 African, 3,928 African"

您还可以使用stringr中的str_replace_all()通过将命名向量(c(pattern1 = replacement1))传递给它来执行多个替换.

library(tidyverse)

df1 %>%
  mutate(txt = str_replace_all(txt, deframe(df2)))

#                            txt
# 1 896 European, 2,455 European
# 2   591 European, 687 European
# 3 1,968 African, 3,928 African

Data
df1 <- data.frame(txt = c("896 European ancestry cases, 2,455 European ancestry controls",
                          "591 European individuals, 687 European males",
                          "1,968 African American cases, 3,928 African American controls"))

df2 <- structure(list(
V1 = c("European ancestry cases", "European ancestry controls", "European individuals", "European males", "African American cases", "African American controls"),
V2 = c("European", "European", "European", "European", "African", "African")),
class = "data.frame", row.names = c(NA, -6L))

R相关问答推荐

是否可以通过另一个DF的内容过滤数据帧列表?

在集合群体模型中计算时间步依赖的速率/参数

是否有R代码来判断一个组中的所有值是否与另一个组中的所有值相同?

为什么当我try 在收件箱中使用合并功能时会出现回收错误?

行式dppr中的变量列名

R中的子集文件—读取文件名索引为4位数字序列,例如0001到4000,而不是1到4000)

R for循环返回到先前值

R-更新面内部的栅格值

提取具有连续零值的行,如果它们前面有R中的有效值

如何从R ggplot图片中获取SVG字符串?

如何将使用rhandsontable呈现的表值格式化为百分比,同时保留并显示完整的小数精度?

自动STAT_SUMMARY统计与手动标准误差之间的差异

如何在ggplot2中创建多个y轴(每个变量一个)

将列的值乘以在不同数据集中找到的值

有没有办法将基于每个值中出现的两个关键字或短语的字符串向量重新编码为具有这两个值的新向量?

网络抓取新闻标题和时间

在r中整理图例和堆叠图的问题

在使用SliderInput In Shiny(R)设置输入数据的子集时,保留一些情节痕迹

需要一个函数来在第一行创建一个新变量,然后用新变量替换一个不同的变量(对于多行)

如何合并不同列表中的数据文件,包括基于名称的部分匹配,而不是一对一等价