R:直接把"Feed"结果变成一个IF语句

R: Directly "Feed" Results into an IF STATEMENT

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

> 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”的 returning 值为“1,2,3”。但我希望它对应于 height_quantiles 帧的 return 值,例如“3.75、3.71、4.12”。

有人可以告诉我怎么做吗?

谢谢

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

还有一个更好的方法是使用连接或 match

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

merge(test, height_quantiles)