简体   繁体   English

在R中创建变量时如何确定因子水平顺序

[英]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 . 我正在创建一组具有相同级别的变量: 0 or 1 However when I print them sometimes the table starts with value 0 and sometimes with 1 . 但是,当我打印它们时,表有时以0开头,有时以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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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