【问题标题】:R: Directly "Feed" Results into an IF STATEMENTR:直接将结果“输入”到 IF 语句中
【发布时间】:2021-11-26 06:53:37
【问题描述】:

我正在使用 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”。

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

谢谢

【问题讨论】:

    标签: r dplyr data-manipulation


    【解决方案1】:

    您需要从第二列中提取数据,即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)
    

    【讨论】:

    • @Ronak Shah:谢谢你的回答!我将不得不记住 R 中的这个“匹配”命令。它看起来非常有用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2018-01-11
    • 2013-10-18
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多