0

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.

Ana
  • 1,132
  • 3
  • 12
  • 20
  • Can you give a sample of the data, for a complete reproducible example? – iod Oct 30 '18 at 20:49
  • Not sure if this is what you mean, but `forcats::as_factor` creates labels in the order in which they occur in the data – camille Oct 30 '18 at 20:54

1 Answers1

0

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
Jordo82
  • 537
  • 4
  • 12