How to Convert Integer into Categorical Data in R

How to convert integer into categorical data in R?

Have a look at ?as.factor. In your case

mydata$COR <- as.factor(mydata$COR)

Change Numeric Variables to be Categorical in R

(Just making my comment an answer)

You can use

data$ZIP <- as.character(data$ZIP) 

or

data$ZIP <- as.factor(data$ZIP)

depending on the variable type you prefer to work with.

Got numbers as categorical data in R

Try this. Your variable looks like character format. You need to transform it to numeric. If it is factor, you can use x = as.numeric(as.character(GreymattervolumeValue)). Here the code:

library(ggplot2)
#Code 1
p <-ggplot(quibimdatos) +
geom_histogram(aes( x = as.numeric(GreymattervolumeValue)))

The other option would be:

#Code 2
p <-ggplot(quibimdatos) +
geom_histogram(aes( x = as.numeric(as.character(GreymattervolumeValue))))

How to convert integer to factor?

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"

Turn strings into categorical variables in R without specifying column names

I suggest looking into the dplyr package. You can do this pretty quickly with mutate_if

df <- data.frame(
fruits = c('apple', 'pear', 'apple', 'orange', 'orange'),
cars = c('volvo', 'bwm', 'bmw', 'volvo', 'fiat'),
stringsAsFactors = FALSE
)

str(df)

'data.frame': 5 obs. of 2 variables:
$ fruits: chr "apple" "pear" "apple" "orange" ...
$ cars : chr "volvo" "bwm" "bmw" "volvo" ...

library(dplyr)
dfFactors <- df %>%
mutate_if(is.character, as.factor)

str(dfFactors)

'data.frame': 5 obs. of 2 variables:
$ fruits: Factor w/ 3 levels "apple","orange",..: 1 3 1 2 2
$ cars : Factor w/ 4 levels "bmw","bwm","fiat",..: 4 2 1 4 3

How to force numeric variable to read as categorical in r using summary() ?


> x <- seq(1:10)

> summary(as.factor(x))
1 2 3 4 5 6 7 8 9 10
1 1 1 1 1 1 1 1 1 1

Or, if you want to permanently assign x as categorical variable in a dataframe named mydata, do this before the summary() call:

mydata$x <- factor(mydata$x) 

(Spending an hour or two with any of the many books or online intros to R and typing out the examples is a smart investment and saves a lot of time.)



Related Topics



Leave a reply



Submit