有条件地查找另一个数据框中的值以填充 R 中的列
Conditionally lookup values in another dataframe to fill column in R
我有一个数据框 df1
,其中包含列 age
和 testScore
。我需要第三个 normScore
基于 age
、testScore
和对第二个数据帧 df2
的引用。让我告诉你:
df1
年龄
测试分数
标准分数
78.6
1
87.1
2
df2
年龄开始
年龄结束
测试分数
标准分数
70
79.9
1
15
70
79.9
2
20
80
89.9
1
18
80
89.9
2
24
所以我需要比较 df1
中的 age
与 df2
中的 ageStart
和 ageEnd
然后使用 testScore
df1
to select normScore
in df2
保存normScore
in normScore
column in df1
, 如下:
df1
年龄
测试分数
标准分数
78.6
1
15
87.1
2
24
在 Excel 我会使用 SUMPRODUCT,但我对 R 有点陌生。你能帮我吗?
(我又开始 post 了,因为我弄乱了之前 post 中的表格,对此感到抱歉)
调整此 answer 这可以通过 fuzzyjoin
包实现,如下所示:
library(fuzzyjoin)
library(dplyr)
df1 <- data.frame(
age = c(78.6, 87.1),
testScore = c(1L, 2L)
)
df2 <- data.frame(
ageStart = c(70L, 70L, 80L, 80L),
ageEnd = c(79.9, 79.9, 89.9, 89.9),
testScore = c(1L, 2L, 1L, 2L),
normScore = c(15L, 20L, 18L, 24L)
)
fuzzy_left_join(df1, df2, by = c("testScore", "age" = "ageStart", "age" = "ageEnd"), match_fun = list(`==`, `>=`, `<=`)) %>%
select(age, testScore = testScore.x, normScore)
#> age testScore normScore
#> 1 78.6 1 15
#> 2 87.1 2 24
我有一个数据框 df1
,其中包含列 age
和 testScore
。我需要第三个 normScore
基于 age
、testScore
和对第二个数据帧 df2
的引用。让我告诉你:
df1
年龄 | 测试分数 | 标准分数 |
---|---|---|
78.6 | 1 | |
87.1 | 2 |
df2
年龄开始 | 年龄结束 | 测试分数 | 标准分数 |
---|---|---|---|
70 | 79.9 | 1 | 15 |
70 | 79.9 | 2 | 20 |
80 | 89.9 | 1 | 18 |
80 | 89.9 | 2 | 24 |
所以我需要比较 df1
中的 age
与 df2
中的 ageStart
和 ageEnd
然后使用 testScore
df1
to select normScore
in df2
保存normScore
in normScore
column in df1
, 如下:
df1
年龄 | 测试分数 | 标准分数 |
---|---|---|
78.6 | 1 | 15 |
87.1 | 2 | 24 |
在 Excel 我会使用 SUMPRODUCT,但我对 R 有点陌生。你能帮我吗? (我又开始 post 了,因为我弄乱了之前 post 中的表格,对此感到抱歉)
调整此 answer 这可以通过 fuzzyjoin
包实现,如下所示:
library(fuzzyjoin)
library(dplyr)
df1 <- data.frame(
age = c(78.6, 87.1),
testScore = c(1L, 2L)
)
df2 <- data.frame(
ageStart = c(70L, 70L, 80L, 80L),
ageEnd = c(79.9, 79.9, 89.9, 89.9),
testScore = c(1L, 2L, 1L, 2L),
normScore = c(15L, 20L, 18L, 24L)
)
fuzzy_left_join(df1, df2, by = c("testScore", "age" = "ageStart", "age" = "ageEnd"), match_fun = list(`==`, `>=`, `<=`)) %>%
select(age, testScore = testScore.x, normScore)
#> age testScore normScore
#> 1 78.6 1 15
#> 2 87.1 2 24