【发布时间】:2021-06-02 12:22:05
【问题描述】:
所以,我有一些学生写了一份谷歌表格调查。调查采用字符串形式,他们在其中选择一个下拉菜单,其中包含以下选项:
我不觉得难过
有时我会感到难过
我经常感到难过
总觉得难过
这是一种仿照贝克抑郁量表的问题。每个项目分别与一个 0,1,2,3 相关联。
其中有大约 20 个变量。
所以,我有 2 个数据框。
df1 有调查数据(回复字符串)。这是其中的 2 个变量
head(df1[1:7,c('sad','optimism')])
sad optimism
<chr> <chr>
1 Throughout the day I sometimes feel sad I am somewhat optimistic about my future
2 Throughout the day I sometimes feel sad I am somewhat optimistic about my future
3 Throughout the day I sometimes feel happy I feel discouraged about the future
4 Throughout the day I sometimes feel happy I am optimistic about my future
5 Throughout the day I sometimes feel happy I am somewhat optimistic about my future
6 Throughout the day I sometimes feel happy I am somewhat optimistic about my future
7 Throughout the day I sometimes feel happy I feel discouraged about the future
df2 有一个条件键
head(df2[1:4,c('sad','optimism')])
sad optimism
<chr> <chr>
1 Throughout the day I feel happy I am optimistic about my future
2 Throughout the day I sometimes feel … I am somewhat optimistic about my future
3 Throughout the day I sometimes feel … I feel discouraged about the future
4 Throughout the day I feel sad I feel the future is hopeless and that things cannot …
每个数据帧中的变量名称都相同。
我想使用 dplyr 的 case_when 使用管道从 df1 中获取每个变量,并将其与 df2 中的相应列进行比较。
以下代码实际上可以将字符串转换为数字,但如果您注意到 case_when conditional 会检查数据帧的整行,这完全没有必要。我想用键的df2$sad 简单地检查调查中的df1$sad 变量。
df1 %>% mutate(across(x,~case_when(
# The following lines of code checks a given record statement
# with ALL columns. Should only check indexed column
. %in% df2[2,] ~ 0, #checks across all variables in df2; I just want to check a single column
. %in% df2[3,] ~ 1,
. %in% df2[4,] ~ 2,
. %in% df2[5,] ~ 3)))
所以,一些问题:
- 我不确定 case_when 可以做到这一点
- 如果是这样,我想知道是否需要使用点符号
- 或者也许有更好的解决方案
我(还)不明白的可能答案
[1.]: dplyr case_when 这可能是最好的选择...不知道如何理解这一切。
[2.]:dplyr case_when Programmatically
- dplyr case_when multiple cases 看起来很有希望
【问题讨论】:
标签: r dplyr case-when programmatically