Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integer to factor? [duplicate]

Tags:

r

Say I have the following df

x<-c(1,3,2,4,1,3,2,4,1,3,2,4)
y<-c(rnorm(12))
df<-data.frame(x,y)

x is integer and I try to convert it to a factor using the suggestion from the R cookbook:

df[,'x']<-factor(df[,'x'])

But it still remains an integer. I have tried a solution found on the forum

df[,'x']<-lapply(df[,'x'], factor)

but it did not work either. Thanks.

like image 367
Vasile Avatar asked Jul 01 '15 15:07

Vasile


People also ask

How do you convert an integer into a factor?

Converting Numeric value to a Factor For converting a numeric into factor we use cut() function. cut() divides the range of numeric vector(assume x) which is to be converted by cutting into intervals and codes its value (x) according to which interval they fall.

How can I convert the data type of a variable from an integer to a factor?

To convert the data type of all columns from integer to factor, we can use lapply function with factor function.

How do I change data from numeric to factor in R?

In R, you can convert multiple numeric variables to factor using lapply function. The lapply function is a part of apply family of functions. They perform multiple iterations (loops) in R. In R, categorical variables need to be set as factor variables.

What is the difference between character and factor in R?

The main difference is that factors have predefined levels. Thus their value can only be one of those levels or NA. Whereas characters can be anything.


1 Answers

It seems that your original solution works. Check the typeof() as well as the class():

x<-c(1,3,2,4,1,3,2,4,1,3,2,4)
y<-c(rnorm(12))
df<-data.frame(x,y)
typeof(df$x)
#"double"    
class(df$x)
#"numeric"
df[,'x']<-factor(df[,'x'])
typeof(df$x)
 #"integer"
class(df$x)
#"factor"
like image 95
erasmortg Avatar answered Nov 15 '22 06:11

erasmortg