Search code examples
rr-xlsx

data type with read.xlsx in R


I am using xlsx library in R to read a excel sheet. I used the following command. My data are numeric/floats with NA for missing values and first column as name (string/character type). However, all the column are of type character and I could not find if I can somehow specify NA values as missing values. Any suggestions on how to deal with the issue?

df=read.xlsx(file0, sheetName = 'sheet1', as.data.frame = TRUE, 
             header = TRUE, use.value.labels=FALSE, stringsAsFactors=FALSE)

Solution

  • You can also try

    df[]=lapply(df,type.convert,as.is=TRUE)
    

    type.convert will attempt to find the appropriate class of each column and convert accordingly. Without the option as.is=TRUE it will convert the character columns to factors. It also handles NA strings. The default option na.strings="NA" should be ok for you.