简体   繁体   中英

R: How to recode binary factor levels (0=0, 1=1) in BASE R

When I read in a csv file, there's a binary target.

as.factor is assigning the 0's and 1's backwards (index wise).

I want 0='0' and 1 = '1'

I found the function Recode in the Car package (or maybe it was dplyr), and another one in Tidyverse. Both of those packages conflict with other packages and break my R code.

How do I recode the binary factor levels in BASE r?

Thanks for your help.

We can specify the levels and the corresponding labels in factor .

df1$col1 <- factor(df1$col1, levels = c(0, 1), labels = c('0', '1'))

In this way, it can be changed to any order

factor(df1$col1, levels = c(0, 1), labels = c('1', '0'))

Or

factor(df1$col1, levels = c(0, 1), labels = c('2', '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