r - 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”。
有人可以告诉我如何做到这一点吗?
谢谢
解决方案
您需要从第二列 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)
推荐阅读
- assembly - 如何在ARM中进行浮点计算?
- visual-studio-code - 如何使用 vscodevim 在 VS Code 中浏览文件树?
- r - 使用 dplyr 在长格式数据上计算因子水平和数值的唯一出现次数
- jmeter - 如何在 JMeter 的单个脚本中对多个字段执行验证
- bash - 即使命令失败,退出状态也会返回“0”
- c# - 从 Intranet 网页中提取链接
- c# - 如何订阅 WndProc 方法并接收它的参数
- javascript - 如何使用javascript剪切文本?
- node.js - express-validator: LHS 括号
- dart - Dart:让流中抛出的异常传播并在调用者中捕获它