[英]Recoding a variable by a double conditional in dplyr using mutate and case_when
[英]R: Recoding variables using recode, mutate and case_when
我想為數據集中core.vars定義的以下變量重新編碼以下值<4 = -1,4 = 0,> 4 = 1,並且仍將其余變量保留在數據框中。
temp.df <- as.tibble (mtcars)
other.vars <- c('hp', 'drat', 'wt')
core.vars <- c('mpg', 'cyl', 'disp')
temp.df <- rownames_to_column (temp.df, var ="cars_id")
temp.df <- temp.df %>% mutate_if (is.integer, as.numeric)
我嘗試了很多方法來實現它。 使用case_when
, mutate
, recode
但沒有運氣。 recode
需要一個向量,所以我的想法是使用case_when
或mutate
為每個感興趣的變量創建一個向量,然后重新編碼這些值。 但他們失敗了。
temp.df <- temp.df %>%
mutate_at(.vars %in% (core.vars)), '< 4' = "-1", '4' = "0", '> 4' = "1")
錯誤:“temp.df < - temp.df%>%mutate_at(.vars%in%(core.vars))中的意外',',”
temp.df <- temp.df %>%
mutate_at(vars(one_of(core.vars)), '< 4' = "-1", '4' = "0", '> 4' = "1")
繼承錯誤(x,“fun_list”):缺少參數“.funs”,沒有默認值
temp.df <- temp.df %>%
mutate (temp.df, case_when (vars(one_of(core.vars)), recode ('< 4' = "-1", '4' = "0", '> 4' = "1")))
mutate_impl(.data,dots)中的錯誤:列
temp.df
是不受支持的類data.frame
temp.df <- temp.df %>%
case_when (vars(one_of(core.vars)), recode ('< 4' = "-1", '4' = "0", '> 4' = "1"))
recode.character出錯(
< 4
=“ - 1”,4
=“0”,> 4
=“1”):缺少參數“.x”,沒有默認值
temp.df <- temp.df %>% rowwise() %>% mutate_at(vars (core.vars),
funs (case_when (
recode(., '< 4' = -1, '0' = 0, '>4' = 1)
))) %>%
ungroup()`
mutate_impl(.data,dots)出錯:評估錯誤:案例1(
recode(mpg,
<4= -1,
= 0,
> 4= 1)
)必須是雙邊公式,而不是雙精度公式。 此外:警告消息:在recode.numeric(MPG,< 4
= -1,0
= 0,>4
= 1):的NA受到脅迫引入
論壇上的先前問題包括如何針對單個變量執行此操作,但是如上所述,我有100個變量和300個樣本,因此不能逐行輸入它們。
理想情況下,不創建一個單獨的數據框然后進行連接,或者像mutate那樣創建多個單獨的變量會很好。
我確信這有一個for循環和/或ifelse方法,但是試圖使用tidyverse來實現目標。 任何的意見都將會有幫助。
temp.df %>%
mutate_at(vars(one_of(core.vars)),
function(x) case_when(
x < 4 ~ -1,
x == 4 ~ 0,
x > 4 ~ 1
))
產量
# A tibble: 32 x 12
cars_id mpg cyl disp hp drat wt qsec vs am gear carb
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Mazda RX4 1 1 1 110 3.9 2.62 16.5 0 1 4 4
2 Mazda RX4 Wag 1 1 1 110 3.9 2.88 17.0 0 1 4 4
3 Datsun 710 1 0 1 93 3.85 2.32 18.6 1 1 4 1
4 Hornet 4 Drive 1 1 1 110 3.08 3.22 19.4 1 0 3 1
5 Hornet Sportabout 1 1 1 175 3.15 3.44 17.0 0 0 3 2
6 Valiant 1 1 1 105 2.76 3.46 20.2 1 0 3 1
7 Duster 360 1 1 1 245 3.21 3.57 15.8 0 0 3 4
8 Merc 240D 1 0 1 62 3.69 3.19 20 1 0 4 2
9 Merc 230 1 0 1 95 3.92 3.15 22.9 1 0 4 2
10 Merc 280 1 1 1 123 3.92 3.44 18.3 1 0 4 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.