我想创建一个函数,该函数采用数据帧df1的行(具有列x1,x2,x3),并且此函数的输出是数据帧df2的子集(具有y1,y2列),该子集为根据df1行中的值计算得出。我想将此功能应用于df1的每一行,并将结果数据帧(df2的子集)堆叠在一个大数据帧中。示例如何使用for循环来完成: df1的示例:
x1 x2 x3
a 3.1 4.5
b 9.0 10.1
a 9.0 20.0
c 1.1 6.0
df2示例:
y1 y2
a 4.0
a 10.0
a 3.5
b 9.8
b 9.5
b 25.0
c 8.2
c 12.0
进行此处理的for循环示例:
desired_df = df2[1, ]
for (i in 1:nrow(df1)) {
subset = filter(df2, y1 == df1[i, "x1"] & y2 > df1[i, "x2"] & y2 < df1[i, "x3"])
desired_df = rbind(desired_df, subset)
}
desired_df = desired_df[-1, ]
所需的数据帧是:
y1 y2
a 4.0
a 3.5
b 9.8
b 9.5
a 10.0
根据df1中的值,子设置可以提供不同长度的数据帧(有时没有元素) 问题是:如何编写这种向量化形式的子集和追加过程,而无需for循环?
答案 0 :(得分:0)
好像我们需要一个fuzzy_join
library(dplyr)
library(fuzzyjoin)
fuzzy_inner_join(df1, df2, by = c('x1' = 'y1', 'x2' = 'y2', 'x3' = 'y2'),
match_fun = list(`==`, `<=`, `>`)) %>%
select(names(df2))
# y1 y2
#1 a 4.0
#2 a 3.5
#3 b 9.8
#4 b 9.5
#5 a 10.0
df1 <- structure(list(x1 = c("a", "b", "a", "c"), x2 = c(3.1, 9, 9,
1.1), x3 = c(4.5, 10.1, 20, 6)), class = "data.frame", row.names = c(NA,
-4L))
df2 <- structure(list(y1 = c("a", "a", "a", "b", "b", "b", "c", "c"),
y2 = c(4, 10, 3.5, 9.8, 9.5, 25, 8.2, 12)), class = "data.frame",
row.names = c(NA,
-8L))