简体   繁体   中英

How to fix factor level order at the time of variable creation in R

I am creating a set of variables all having the same levels: 0 or 1 . However when I print them sometimes the table starts with value 0 and sometimes with 1 . I'd like to see if I can lock the order when creating them. Here is how they are created:

list = ('a','b','c')
df <- df %>% mutate_at(.vars = list, .funs = funs(yn = ifelse(. == 0,0,1)))

Also what I use for fixing the order is below:

neworder = ('0','1')
df <- arrange(transform(df, a=factor(a, levels = neworder)),a)

but I cannot combine the two procedures.

Perhaps you were getting an error from mixing numeric and character values? This works for me:

library(tidyverse)

df <- data.frame(a = rbinom(10, 1, 0.5),
                 b = rbinom(10, 1, 0.5),
                 c = rbinom(10, 1, 0.5))

list <-  c('a','b','c')
neworder <- c(0, 1)

df <- df %>% 
  mutate_at(.vars = list, .funs = funs(yn = factor(ifelse(. == 0,0,1), levels = neworder)))



str(df)
'data.frame':   10 obs. of  6 variables:
$ a   : int  0 1 0 1 1 1 1 1 0 1
$ b   : int  1 0 0 0 0 0 0 0 0 0
$ c   : int  1 1 1 1 1 0 0 0 0 0
$ a_yn: Factor w/ 2 levels "0","1": 1 2 1 2 2 2 2 2 1 2
$ b_yn: Factor w/ 2 levels "0","1": 2 1 1 1 1 1 1 1 1 1
$ c_yn: Factor w/ 2 levels "0","1": 2 2 2 2 2 1 1 1 1 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM