我有以下样本数据框:
df <- structure(list(PC1 = c(1.08553700088979, 3.0948497436612,
-0.997456334603069,
1.41407630966724, 0.287288941434462, -0.304145457046063, 0.0540331738096902,
0.276994168448363, -0.178887591197422, 1.03793040779083, -0.964485366085487,
0.781189811085296, -0.360466840689429, -2.25639643892807,
-0.688600791894463,
1.05031184739218, 3.30341296998208, 0.265388275042453, 0.187534314978584,
2.58042550274586, 0.564788667016578), PC2 = c(-0.560967999647005,
0.856204454728214, 0.720760276550347, 1.75595629874967, -0.707834522512927,
0.891530126176209, 0.631768747109977, -0.845237959897621,
-0.412613566320007,
-0.159362864836617, -0.569253016944671, -0.0181844049717689,
-0.0218393445421908, 1.86197538876216, -0.263011388351398,
0.0582985416071711,
1.7585346351499, 1.74997701136744, 0.723398654405442, -0.482322211724498,
-0.240535930597667), PC3 = c(0.36287528575844, -2.01764685704277,
-0.408829080806452, 0.97914722241214, -0.665892667247256,
-0.242401102421392,
0.497651711177106, 1.26726883331746, 1.27889899812577, 0.54485872382572,
0.191895005811088, 0.381351220912963, -0.613213748902156,
0.0685178101199476,
0.532000414181072, 1.19230092657081, 1.48731243525717, 1.16110479193897,
0.486880645956999, -2.69479147849705, 0.169949194117217)), row.names = c(NA,
-21L), class = c("tbl_df", "tbl", "data.frame"))
我想根据另一个数据框 f1
中给出的关于 PC1
的条件集过滤 df
的行:
f1 <- structure(list(xmin = c(-3.59811981997059, -3.10182743100913,
-2.8536812365284, 2.8536812365284, 3.59811981997058), xmax =
c(-3.34997362548985,
-2.8536812365284, -2.60553504204766, 3.10182743100912, 3.84626601445132
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
应根据f2
对PC2进行过滤。
f2 <- structure(list(xmin = c(-2.56910324629848, -2.37879930212822,
2.56910324629848, 2.949711134639), xmax = c(-2.37879930212822,
-2.18849535795797, 2.75940719046874, 3.14001507880926)), row.names = c(NA,
-4L), class = c("tbl_df", "tbl", "data.frame"))
换句话说,数据框中
df
的列 PC1
中的值必须介于 -3.6 和 -3.35 之间或介于 -3.1 和 -2.85 之间,以此类推,而 PC2
的值必须介于 -2.57 和 -2.38 之间,以此类推。对于 df
的每一列,我都有一个相应的数据框告诉我如何筛选相应的列。
当然,我也可以写出条件:
df %>% filter(PC1 > -3.6 & PC1 < -3.35 | PC1 > -3.1 & PC1 < -2.85 & PC2 > -2.57 & PC2 < -2.38 ....),
并且对每一列重复此操作。但最终我将有许多条件,这是不切实际的。
是否有更短更有效的方法?
谢谢!
findInterval
。例如,第一列的条件可能是findInterval(df$PC1,as.vector(t(f1)))%%2==1
。您可以轻松地使用Map
或循环等将所有条件包装起来,然后再用Reduce
组合它们。 - nicola