Search code examples
rencodesapplydatamatrix

convert df from factor to numeric


I am struggling to convert my dataset into numeric values. The dataset I have looks like this:

customer_id 2012 2013 2013 2014  2015 2016 2017
15251        X     N     U    D     S    C    L

X1 - X7 are marked as factors. The extract from dput(head(df)) is:

    structure(list(`2012` = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("N", 
"X"), class = "factor"), `2013` = structure(c(6L, 6L, 6L, 6L, 
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L
), .Label = c("C", "D", "N", "S", "U", "X"), class = "factor"), 
    `2014` = structure(c(8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 
    8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L), .Label = c("C", 
    "D", "L", "N", "R", "S", "U", "X"), class = "factor"), ... 

I would like to have the data in numeric values, but I don't know how I can transform them accordingly. The goal is that I can feed the df into a heatmap so that I can visually explore the differences. To my knowledge, this is only possible with a numeric matrix. Because I get the error Heatmap.2(input, trace = "none", : `x' must be a numeric matrix

Does someone have any idea?

Many Thanks for your support!


Solution

  • it's do-able. I think it would help next time to include the complete df. The heatmap.2 does not work because you gave it a character matrix. It's a bit more complicated to display the legend for color to letters using heatmap.2, I suggest something below using ggplot

    library(ggplot2)
    library(dplyr)
    library(viridis)
    
    # simulate data
    df = data.frame(id=1:5,
    replicate(7,sample(LETTERS[1:10],5)))
    colnames(df)[-1] = 2012:2018
    
    #convert to long format for plotting and refactor
    df <- df %>% pivot_longer(-id) %>%
    mutate(value=factor(as.character(value),levels=sort(levels(value))))
    
    #define color scale
    # sorted in alphabetical order
    present_letters = levels(df$value)
    COLS = viridis_pal()(length(present_letters))
    names(COLS) = present_letters
    
    #plot
    ggplot(data=df,aes(x=name,y=id,fill=value)) + 
    geom_tile() + 
    scale_fill_manual(values=COLS)
    

    enter image description here