我想对数据框 1 ( df1
) 中包含数据框 2 ( ) 中某一列的字符串的行进行子集化df2
。问题是 file1 在同一列中会有多个字符串。我尝试了几种不同的 subset 和grep
,但都没有成功。
以下是文件的示例以及我想要实现的结果(两者都可以):
df1
1 apple A,C,D,F
2 pear A,D
3 plum B,F
4 banana K,P,Z
5 orange B,C,D,H
df2
A Jan
B Feb
C Mar
D Apr
E May
F Jun
G Jul
H Aug
I Sept
J Oct
结果 1
1 apple A,C,D,F
2 pear A,D
3 plum B,F
5 orange B,C,D,H
结果 2
1 apple A,C,D,F Jan,Mar,Apr,Jun
2 pear A,D Jan,Apr
3 plum B,F Feb,Jun
5 orange B,C,D,H Feb,Mar,Apr,Aug
答案1
我不确定这是否与主题相关,但您可以通过将第一列中的值df2
与 a相结合|
,然后使用grep
在第二列中找到其中任何一个,轻松实现第一个期望的输出df1
df1[grep(paste(df2$V1, collapse = "|"), df1$V2), ]
# V1 V2
# 1 apple A,C,D,F
# 2 pear A,D
# 3 plum B,F
# 5 orange B,C,D,H
对于第二个输出,还需要做更多工作。我们可以用第二个变量替换所有的,
by ,然后在折叠 by 时查找它们,并连接回,其中一些如下所示|
df1
df2
,
df1
res <- sapply(df1$V2, function(x) {
res <- df2$V2[grep(gsub("\\,", "|", x), df2$V1)]
if(length(res)) paste(x, paste(res, collapse = ",")) else NA
})
cbind.data.frame(V1 = df1[which(!is.na(res)), 1], V2 = na.omit(res))
# V1 V2
# 1 apple A,C,D,F Jan,Mar,Apr,Jun
# 2 pear A,D Jan,Apr
# 3 plum B,F Feb,Jun
# 4 orange B,C,D,H Feb,Mar,Apr,Aug
我读过的数据集
df1 <- "banana", "orange", "pear", "plum"), class = "factor"), V2 = structure(c(1L,
2L, 4L, 5L, 3L), .Label = c("A,C,D,F", "A,D", "B,C,D,H", "B,F",
"K,P,Z"), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-5L))
df2 <- structure(list(V1 = structure(1:10, .Label = c("A", "B", "C",
"D", "E", "F", "G", "H", "I", "J"), class = "factor"), V2 = structure(c(4L,
3L, 7L, 1L, 8L, 6L, 5L, 2L, 10L, 9L), .Label = c("Apr", "Aug",
"Feb", "Jan", "Jul", "Jun", "Mar", "May", "Oct", "Sept"), class = "factor")), .Names = c("V1",
"V2"), class = "data.frame", row.names = c(NA, -10L))