Home > Software engineering >  Convert table to dataframe without factors
Convert table to dataframe without factors

Time:11-08

I wish to convert a table into a dataframe without converting character vectors to factors. However, the stringsAsFactors parameter doesn't work as expected in this case.

#create table
(t <- table(c("a", "b"), c("c", "c")))   
#    c
#  a 1
#  b 1

#convert table into dataframe
(df <- data.frame(t, stringsAsFactors=F))
#  Var1 Var2 Freq
#1    a    c    1
#2    b    c    1

#df column is factor
class(df$Var1)
[1] "factor"

CodePudding user response:

You need as.data.frame instead, data.frame won't modify the original factors:

> df <- as.data.frame(t, stringsAsFactors=F)
> class(df$Var1)
[1] "character"
> 
  • Related