Итак, у меня есть несколько студентов, которые написали анкету в Google. Опрос находится в строковой форме, где они выбирают раскрывающееся меню с такими параметрами, как:
Мне не грустно
Иногда мне грустно
Мне часто грустно
Мне все время грустно
Это тип вопроса, смоделированный на основе инвентаризации депрессии Бека. Каждому элементу соответствует 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 …
Имена переменных одинаковы во всех фреймах данных.
Я хочу использовать case_when
dplyr, используя каналы, чтобы взять каждую переменную из df1 и сравнить ее с соответствующим столбцом в df2.
Следующий код действительно работает при преобразовании строки в число, но если вы заметили, что case_when conditional
проверяет всю строку фрейма данных, что совершенно не нужно. Я хочу просто проверить переменную df1$sad
из опроса с df2$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 Программно
- dplyr case_when multiple cases выглядит многообещающим