簡體   English   中英

在R中創建變量時如何確定因子水平順序

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

我正在創建一組具有相同級別的變量: 0 or 1 但是,當我打印它們時,表有時以0開頭,有時以1開頭。 我想看看在創建訂單時是否可以鎖定訂單。 它們的創建方式如下:

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

另外,我用於確定訂單的內容如下:

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

但是我不能將這兩個過程結合在一起。

也許您將數字和字符值混合會出錯? 這對我有用:

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