Hugues Fontenelle Hugues Fontenelle - 3 months ago 17
R Question

mix `stringsAsFactors` in dataframe

I'm trying to create a R dataFrame where some columns would be treated as Factors and others as Strings.

fruits <- data.frame(fruit = character(), descr = character())
fruits <- rbind(fruits, data.frame(fruit = "apple", descr = "jjrkgnser"))
fruits <- rbind(fruits, data.frame(fruit = "apple", descr = "aprtgh"))
fruits <- rbind(fruits, data.frame(fruit = "pear", descr = "akjreg"))


Here both columns are treated as Factors, and I end up with as many factors for the
descr
columns as there are rows in the
fruits
dataFrame.

How can
descr
be treated as String, but
fruit
as Factors?
If I use
stringsAsFactors = FALSE
it applies to all columns!

Edit

I hacked this solution, not so elegant:

fruits <- data.frame(fruit = factor(), path = character(), stringsAsFactors = FALSE)
fruits <- rbind(fruits, data.frame(fruit = factor("apple"), path = "jjrkgnser", stringsAsFactors = FALSE))
fruits <- rbind(fruits, data.frame(fruit = factor("apple"), path = "aprtgh", stringsAsFactors = FALSE))
fruits <- rbind(fruits, data.frame(fruit = factor("pear"), path = "akjreg", stringsAsFactors = FALSE))


Doing

> str(fruits)
'data.frame': 3 obs. of 2 variables:
$ fruit: Factor w/ 2 levels "apple","pear": 1 1 2
$ path : chr "jjrkgnser" "aprtgh" "akjreg"


fits the requirement. Is there a nicer way?

Answer
# creating the dataset (no usage of rbind if possible) with factor columns by default
fruits <- data.frame(fruit = c("apple", "apple", "pear"), 
                     path = c("jjrkgnser", "aprtgh", "akjreg"))

# transform this column to a character vector
fruits$path = as.character(fruits$path)