简体   繁体   中英

R character vectors into factors

I have a character vector of the type a<- c('ES1-5', 'ES14-26', 'ES27-38', 'ES6-13', 'SA1-13', 'SA14-25') and it is a column of a dataframe.

What I would like to do is to transform into a factor with levels 1,2,3,4,5,6 and subsequently transform into a numerical vector of 1,2,3,4,5,6 and colbind into the dataframe.

Could someone give me an elegant way to do this please.

You can use as.numeric(as.factor))

##Some random data##
a<- c('ES1-5', 'ES14-26', 'ES27-38', 'ES6-13', 'SA1-13', 'SA14-25')
x <- tibble(x = rnorm(6),
                y = rnorm(6),
                a = a) ##Append vector a as column in a dataframe

##Make a into a factor and append to the dataframe
x$a_factor <- as.numeric(factor(x$a))
x

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