R ~ dplyr::case_when %in% 35:39,仅选择整数(如 35.0),但不选择带有分数的值,例如



Background

我正在尝试根据各种血液水平和其他因素(如年龄)对参与者进行子集,然后对这些结果进行评分。

#1 问题是%in% 运算符仅子集整数值(例如年龄 35.0 或 38.0),而不是具有 .0 以外的 1/10 分数的有理数,例如 48.6 或 56.7。

#2 问题也适用于 %in% 和分数。在这种情况下,范围为 1.29:1.55 的 %in% 仅选取正好为 1.29 或 1.55 的值,但不包含介于两者之间的值。

我是否应该以某种方式向 R 指定我正在用它们的 1/10 分数对值进行子集化?当值是整数时,该范围工作得很好,例如 %in% 200:205 将子集值为 200、201、202、203、204、205。然而,出于某种原因,如果我想选择一个范围 %in%

20.0:20.5,它会给我 20.0 和 20.5,而不是 20.0、20.1、20.2、20.3、20.4 和 20.5。
File.Score <- File %>%
filter(sex == "FEMALE") %>%
mutate(Score.Age = case_when(age_sc %in% 35:39 ~ 2,
age_sc %in% 40:44 ~ 4,
age_sc %in% 45:49 ~ 5,
TRUE ~ 0))
File.Score <- File %>%
filter(sex == "FEMALE") %>%
mutate(Score.HDL = case_when(HDL > 1.55 ~ -2,
HDL %in% 1.29:1.55 ~ -1,
HDL %in% 1.16:1.29 ~ 0,
HDL %in% 0.9:1.16 ~ 1,
HDL < 0.9 ~ 2))
ISSUE 1
#Range of ages that should be scored
head(File$Age, 50)
[1] 42.3 26.3 29.2 59.8 36.1 43.0 56.7 48.6 47.0 42.2 38.0
#Ages that are scored 
head(File.Score$Score.Age, 11)
[1] NA NA NA NA NA 4 NA NA 5 NA 2
#In other words, only the integers are chosen with a 1/10 fraction of 0.
ISSUE 2
#Range of HDL-values that should be scored
head(File$HDL, 11)
[1] 1.67 1.73 2.05 0.95 1.38 1.60 1.51 1.29 1.34 1.27 1.18
#HDL-values scored
head(File.Score$Score.HDL, 11)
[1] -2 -2 -2 NA NA NA NA -1 NA NA NA
#Only the values that are specified by > -operator and those at the edges 
of the range are subset. Values between 1.29 and 1.55 are not subset.

当我尝试使用ifelse而不是case_when时,也出现了同样的问题。

我可能应该在代码中添加一些规范,但我无法弄清楚它可能是什么。

  • 我使用 Rstudio 版本 1.1.447
  • 我使用 dplyr 版本 0.8.0.1
  • 所有值都是数字 as.doubles,而不是 as.integers。

谢谢格雷戈尔!

事实证明,between是解决问题的方法。

File.Score <- File %>%
filter(sex == "FEMALE") %>%
mutate(Score.Age = case_when(between(age_sc, 35, 39) ~ 2,
between(age_sc, 40, 44) ~ 4,
between(age_sc, 45, 49) ~ 5,
TRUE ~ 0))

相关内容

最新更新