r - R for循环忽略条件if语句
问题描述
我正在使用一个数据集,如果值不丢失,我需要 R 跳过它。我试过制作一个 for 循环,但 R 忽略了我的逻辑。我看过其他 for 循环帖子,但它们不涉及条件被忽略。
这是一个示例数据集:
library(dplyr)
my_problem <- tibble(name = c("Joe", "Joseph", "Joey"),
score1 = c(2, 7, 12),
score2 = c(NA, 5, 10))
这是我想要的样子:
solution <- tibble(name = c("Joe", "Joseph", "Joey"),
score1 = c(1, 7, 12),
score2 = c(NA, 5, 10),
score2edit = c(.30103, 5, 10))
如果 score2 列是 NA,这是我的 for 循环,在 score1 上进行 log10() 转换。但是,由于某种原因,代码忽略了我的 if 语句并直接跳转到 else。
for(i in 1:nrow(my_problem)) {
if(is.na(my_problem$score2[i])) {
my_problem$score2edit <- log10(my_problem$score1)
} else {
my_problem$score2edit <- my_problem$score2
}
}
谢谢!如果您还可以解释为什么此循环不起作用,那将非常有帮助。
解决方案
我们可以使用矢量化选项 ( ifelse/if_else/case_when
)
library(dplyr)
my_problem %>%
mutate(score2edit = case_when(is.na(score2) ~ log10(score1), TRUE ~ score2))
# A tibble: 3 x 4
# name score1 score2 score2edit
# <chr> <dbl> <dbl> <dbl>
#1 Joe 2 NA 0.301
#2 Joseph 7 5 5
#3 Joey 12 10 10
循环遍历每一行,因此for
如果我们使用它然后对整个数据集进行分配/替换,则每一行中的整列都会被替换
推荐阅读
- android - Android Mutablelivedata 列表项未通知更改
- amazon-web-services - 在云上将集群公开到外部
- javascript - 如何在我的项目构建后自动将 WebPack 输出文件保存到另一个地方
- django - Django migrate cmd 详细信息,用于将特定的应用程序模型迁移到特定的数据库架构
- css - 使用 css 变换的 Cdk 拖动图像
- flutter - 通过 Postman 工作,但不在 Flutter 中工作:使用 GCS 预签名 URL 的 API 调用
- typescript - 如何使用可选变量处理 Typescript 函数重载增长
- r - 如何在悬停单元格时弹出行名
- docker - 带有 TestContainer 的 Kibana docker 无法以“无法从 Elasticsearch 节点检索版本信息”开始。
- c# - 将模型传递到布局页面 MVC