У меня есть множество переменных, которые по сути являются факторами, которые я хотел бы перекодировать как целые числа.
Число переменных - это строка, в которой первый символ представляет собой ди git, что соответствует целому числу, например 2 = I have considered suicide in the past week, but not made any plans.
должно быть 2
. Другие переменные yes
или no
и должны быть 1
или 0
соответственно. Другие, имеют многочисленные уровни, основанные на ряде строк:
none = 0
one = 1
two = 2
three = 3
four or more = 4
Аналогично:
ptsd = 0
depression = 1
generalised anxiety = 2
no diagnosis warranted = 3
И:
Female = 0
Male = 1
Other = 2
Некоторые значения в ячейках NA
и должны оставаться как NA
. Я попытался попробовать следующий код, не пытаясь изменить все переменные (для начала просто):
vars1 <- vars(pastpsyc, pastmed, hxsuicide)
vars2 <- vars(siss, mssi_1)
df_rc <- df %>%
## this works
mutate_at(vars1, ~ (case_when(
. == "yes" ~ 1,
. == "no" ~ 0
))) %>%
## this does not
mutate_at(vars2, ~as.integer(str_extract(vars2, "[0-9]"))) %>%
## nor does this
mutate_at(diag1, ~ (case_when(
. == "ptsd" ~ 0,
. == "depression" ~ 1,
. == "generalised anxiety" ~ 2,
. == "no diagnosis warranted" ~ 3
)))
Но это не удается, и я совершенно тупик, как перекодировать другие переменные.
Как я могу изменить различные строки в нужный мне формат (желательно аккуратно)? Ниже приведен минимально воспроизводимый набор данных.
structure(list(siss = c("2 = I have considered suicide in the past week, but not made any plans.",
"1 = I have had vague thoughts of suicide in the past week.",
"2 = I have considered suicide in the past week, but not made any plans.",
"1 = I have had vague thoughts of suicide in the past week.",
"3 = I have made plans to suicide in the past week, but I haven’t intended to act on these plans."
), mssi_1 = c("1. Weak - unsure about whether he/she wants to die, seldom thinks about death, or intensity seems low.",
"1. Weak - unsure about whether he/she wants to die, seldom thinks about death, or intensity seems low.",
"1. Weak - unsure about whether he/she wants to die, seldom thinks about death, or intensity seems low.",
"1. Weak - unsure about whether he/she wants to die, seldom thinks about death, or intensity seems low.",
"2. Moderate - current desire to die, may be preoccupied with ideas about death, or intensity seems greater than a rating of 1."
), diag1 = c("ptsd", NA, "depression", "generalised anxiety",
"no diagnosis warranted"), pastpsyc = c("yes", NA, "no", NA,
"yes"), pastmed = c("no", "yes", NA, "no", "no"), hxsuicide = c("yes",
NA, "yes", "yes", "yes"), suicide_attempts = c("none", NA, "one",
"two", "four or more"), sex = c("Male", "Other", NA, "Female",
NA)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-5L), spec = structure(list(cols = list(siss = structure(list(), class = c("collector_character",
"collector")), mssi_1 = structure(list(), class = c("collector_character",
"collector")), diag1 = structure(list(), class = c("collector_character",
"collector")), pastpsyc = structure(list(), class = c("collector_character",
"collector")), pastmed = structure(list(), class = c("collector_character",
"collector")), hxsuicide = structure(list(), class = c("collector_character",
"collector")), suicide_attempts = structure(list(), class = c("collector_character",
"collector")), sex = structure(list(), class = c("collector_character",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))