r - R - 创建带有或排除的变量
问题描述
我有一个带有一些变量的数据集,这些变量表明老年人是否可以或不能做某项活动(乘坐公共汽车,洗澡......)。我必须创建一些变量,例如“在 C 组中,老年人需要帮助才能进行2项活动,包括洗澡。” #在D组,长者需要协助进行 包括洗澡和穿衣在内的3项活动。
所以观察不能分为两组。我的数据集是这样的:
bathing take_bus dressing eating
1 4 4 4 3
2 2 1 3 2
3 4 2 4 2
4 5 4 1 2
5 2 4 4 1
数字表示进行该活动的难度级别。我只对 4 级或更高级别感兴趣(年长者根本无法单独进行活动)。
例如,在这里,个人 3 和 4 属于 C 组。个人 1 属于 D 组,但不应属于 C 组。个人 5 不在 C 组,因为他可以一个人洗澡。
我做了这样的事情:
df$is_C <- ifelse(df$bathing >= 4 & (df$dressing >= 4 | df$eating >= 4 |
df$take_bus >= 4), 1, 0)
df$is_C <- factor(x = df$is_C, levels = c(1, 0), labels = "Group_C", "Not_Group_C")
df$is_D <- ifelse(df$bathing >= 4 & df$dressing >= 4 & ( df$eating >= 4 | df$take_bus >= 4), 1, 0)
df$is_D <- factor(x = df$is_D, levels = c(1, 0), labels = "Group_D", "Not_Group_D")
但是,当我这样做时:
>table(df$is_C, df$is_D)
Group_D Not_Group_D
Group_C 683 290
Not_Group_C 0 9650
所以 683 人在 C 组,应该只在 D 组......(可以让人们不在 C 组,也不在 D 组,因为我还有其他变量)。
我应该怎么办???????
谢谢大家的好意和回答!
解决方案
这是一个解决方案。
为了使其更具可读性,定义了两个函数,都返回逻辑值。然后将逻辑值用于组 C 和 D 的互斥。完成后,这些值被强制转换为整数,然后转换为因数。
f_is_C <- function(x, level = 4) x[1] >= level && any(x[-1] >= level)
f_is_D <- function(x, level = 4) all(x[1:2] >= level) && any(x[3:4] >= level)
is_D <- apply(df, 1, f_is_D)
is_C <- apply(df, 1, f_is_C) & !is_D # mutual exclusion
df$is_C <- factor(as.integer(is_C), levels = 1:0, labels = c("Group_C", "Not_Group_C"))
df$is_D <- factor(as.integer(is_D), levels = 1:0, labels = c("Group_D", "Not_Group_D"))
with(df, table(is_C, is_D))
# is_D
#is_C Group_D Not_Group_D
# Group_C 0 2
# Not_Group_C 1 2
推荐阅读
- powershell - Powershell 脚本以使用路径填写 Start in section
- vue.js - Vue.js 动画:离开后输入,而不是同时输入
- python - 如何使用 Wand 更改图片的对比度?
- angularjs - 遍历 Angular $$nextSibling 中的对象
- r - 使用 dplyr 添加子组的增量计数
- mongodb - mongodb索引的唯一性
- pine-script - 如何在 pinescript 上的安全功能(多 TF 指标)中使用输入?
- php - 如何使用 Twig 按重量生成随机结果?
- python - 数据框到字典
- javascript - Array.prototype.flatMap() JS 在测试用例和 repl.it 片段中表现异常,但在浏览器控制台中却没有