1

I just do not understand why my data frame keeps being a factor even if I try to change it to a character.

Here I have a data frame list_attribute$affrete.

affrete
<chr>
Fruits
Apple                
Grape Fruits             
Lemon                
Peach                
Banana               
Orange               
Strawberry               
Apple

And I applied a function to replace some values in list_attribute$affrete to other values using another data frame renaming, which has two columns(Name and Rename).

affrete <- plyr::mapvalues(x = unlist(list_attribute$affrete, use.names = F), 
                           from = as.character(renaming$Name), 
                           to = as.character(renaming$Rename))
affrete <- as.character(affrete)
list_attribute$affrete <- data.frame(affrete)

The data frame renaming looks like this;

 Name        Rename
 <fctr>      <fctr>
 Apple       Manzana          
 Orange      Naranja          
 Lemon       Limon            
 Grape       Uva          
 Peach       Melocoton            
 Pinapple    Anana

And here is list_attribute$affrete after applying these processes above.

affrete
<fctr>
Manzana                
Grape Fruits             
Limon                
Melocoton                
Banana               
Naranja               
Strawberry               
Manzana

Why is this column still a factor? I tried the method discussed here but none of them works. WHY? I'd appreciate for any help!

Makoto Miyazaki
  • 1,743
  • 2
  • 23
  • 39
  • Not sure why you `unlist` the character vector `list_attribute$affrete`. Based on what you said the output of `plyr::mapvalues` should be a character vector as well. No need to do `as.character(affrete)` and `data.frame(affrete)`. Try this as an example `library(plyr); x <- c("a", "b", "c"); x1 = factor(c("a", "c")); x2 = factor(c("A", "C")); mapvalues(x, as.character(x1), as.character(x2))` – AntoniosK Apr 12 '18 at 17:23

2 Answers2

6

By default data.frame has argument stringsAsFactors = TRUE. When you call data.frame(affrete) it converts characters to factors. You can either:

  1. Call data.frame(affrete, stringsAsFactors = FALSE) instead
  2. Set this behaviour off permanently for your session with options(stringsAsFactors = FALSE)
  3. Fix after the fact once it's already in the list with list_attribute$affrete$affrete <- as.character(list_attribute$affrete$affrete)
  4. Use tbls from the tidyverse, so call tibble(affrete) instead. These never convert characters, among other benefits.
Calum You
  • 14,687
  • 4
  • 23
  • 42
1

I think the problem is from list_attribute$affrete <- data.frame(affrete), the default behavior of data.frame() is with stringsAsFactors = TRUE

FENG QI
  • 110
  • 1
  • 8