首页 > 解决方案 > R:直接将结果“输入”到 IF 语句中

问题描述

我正在使用 R 编程语言。我有以下示例 - 有两个数据框(height_quantiles 和 test):

> height_quantiles
  salary_type quant_80
1           A 3.752192
2           B 3.713571
3           C 4.117180

> str(height_quantiles)
'data.frame':   3 obs. of  2 variables:
 $ salary_type: Factor w/ 3 levels "A","B","C": 1 2 3
 $ quant_80   : Named num  3.75 3.71 4.12
  ..- attr(*, "names")= chr [1:3] "80%" "80%" "80%"

> head(test)
       salary     height salary_type
701  1.358904  1.6148796           A
702 -2.702212  1.0604070           A
703  1.534527 -4.0957218           A
704  5.594247  5.7373110           B
705 -1.823547  5.5808484           A
706  7.949913 -0.2021635           C

str(test)
'data.frame':   300 obs. of  3 variables:
 $ salary     : num  1.36 -2.7 1.53 5.59 -1.82 ...
 $ height     : num  1.61 1.06 -4.1 5.74 5.58 ...
 $ salary_type: Factor w/ 3 levels "A","B","C": 1 1 1 2 1 3 2 1 2 3 ...

我正在尝试编写以下代码:

test$height_pred = as.numeric(ifelse(test$salary_type == "A", height_quantiles[1,1], ifelse(test$salary_type == "B", height_quantiles[2,1], height_quantiles[3,1])))

但是 "test$height_pred " 的返回值为 "1,2,3" 。但我希望它返回与 height_quantiles 框架相对应的值,例如“3.75、3.71、4.12”。

有人可以告诉我如何做到这一点吗?

谢谢

标签: rdplyrdata-manipulation

解决方案


您需要从第二列 ie 等中提取数据height_quantiles[1,2]height_quantiles[2,2]现在,您正在从第一列中提取数据。

还有一个更好的方法是使用 join 或match.

test$height_pred <- height_quantiles$quant_80[match(test$salary_type, height_quantiles$salary_type)]

或者

merge(test, height_quantiles)

推荐阅读