Search code examples
rdataframelevels

Set dataframe column type to character instead of factor (default) R


dataf <- data.frame(Alert=logical(),IQR=integer(),Kurtosis=integer(),Entropy=integer(),Skewness=integer(),Sex=character(),Complex=character(),Picos=integer(),PicosFil=integer(),Umbral=integer(),Gama=character(),stringsAsFactors=FALSE)
dataf <- rbind(dataf,list(Alert=FALSE,IQR=2.6938,Kurtosis=1.73447,Entropy=1.76160,Skewness=0.140613,Sex="Mujer",Complex="Slim",Picos=0,PicosFill=0,Umbral=15.708,Gama="Alta"))
dataf <- rbind(dataf,list(Alert=FALSE,IQR=0.179574,Kurtosis=19.0538,Entropy=0.74779,Skewness=1.1355,Sex="Mujer",Complex="Slim",Picos=1,PicosFill=1,Umbral=18.975,Gama="Media"))

I have a problem with Gama, when I put in a new value (string), I get the following error:

Warning message: In [<-.factor(*tmp*, ri, value = "Media") : invalid factor level, NA generated


Solution

  • You need to pass stringsAsFactors=FALSE to your lists. You can see when you add the first line, all the character columns on your df turn into factor

    dataf <- data.frame(Alert=logical(),IQR=integer(),Kurtosis=integer(),Entropy=integer(),Skewness=integer(),Sex=character(),Complex=character(),Picos=integer(),PicosFil=integer(),Umbral=integer(),Gama=character(),stringsAsFactors=FALSE)
    dataf <- rbind(dataf,list(Alert=FALSE,IQR=2.6938,Kurtosis=1.73447,Entropy=1.76160,Skewness=0.140613,Sex="Mujer",Complex="Slim",Picos=0,PicosFill=0,Umbral=15.708,Gama="Alta"), stringsAsFactors=FALSE)
    dataf <- rbind(dataf,list(Alert=FALSE,IQR=0.179574,Kurtosis=19.0538,Entropy=0.74779,Skewness=1.1355,Sex="Mujer",Complex="Slim",Picos=1,PicosFill=1,Umbral=18.975,Gama="Media"), stringsAsFactors=FALSE)