df 的子集基于另一个 df 的匹配项 (R/R Studio)

Subset of df based on matches of another df (R/ R Studio)

我有我的原始数据框,我只想保留其中的某些行。

head(original_df)
  id    roi            mean  sd
1 1102A HarvardOxford 0.4675 0.1345
2 1102A HarvardOxford 0.4456 0.1345
3 1102A HarvardOxford 0.4567 0.788
4 1102A HarvardOxford 0.1231 0.8976
5 1102A Lh_func_3     0.1231 0.8678
6 1102A Lh_func_      0.2342 0.67856

id 列包括主题代码 + 一个“A”或“B”或“C”,具体取决于会话。 我有另一个 df(subs),只有一个变量,其中包括我想保留的 ids(它包含来自原始 df 的所有 id 的选择)。在此数据框中,只有主题代码而没有会话指示器。

head(subs)
         V1
1 1102
2 1103
3 1104
4 1107
5 1110
6 1111

如何只保留原始数据框中与 subs$V1 列匹配的行?

使用 substr.

subset(df1, substr(id, 1, 4) %in% df2$V1)
#      id          x
# 2 1103A  0.2051387
# 4 1103B -0.8920853
# 6 1103C  0.8064977

数据:

df1 <- structure(list(id = c("1102A", "1103A", "1102B", "1103B", "1102C", 
"1103C"), x = c(-0.946458205218808, 0.205138719393085, -0.734810811183742, 
-0.892085335997171, 0.327500189913222, 0.806497715247655)), class = "data.frame", row.names = c(NA, 
-6L))

df2 <- structure(list(V1 = 1103:1105), class = "data.frame", row.names = c(NA, 
-3L))

我会首先在您的原始 data.frame 中创建另一列,仅提取 ID 中的数字。

library(tidyverse)
original.df2 <- mutate(original.df, V1 = substr(id,1,4) ## select only first 4 digits

然后您可以根据文件 subs.

过滤行
filter(original.df2, V1 %in% subs$V1)

应该可以了。