简体   繁体   English

R个字符向量成因

[英]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. 我的字符向量类型为a<- c('ES1-5', 'ES14-26', 'ES27-38', 'ES6-13', 'SA1-13', 'SA14-25')和它是数据框的一列。

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. 我想做的就是将其转换为具有1,2,3,4,5,6级的因子,然后转换为1,2,3,4,5,6的数值向量并合并到数据帧中。

Could someone give me an elegant way to do this please. 有人可以给我一种优雅的方法来做到这一点。

You can use as.numeric(as.factor)) 您可以使用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

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

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