0

as a new R user I got a lot of doubts and need some help.

I loaded my sheet from excel using the following function, xlsx, however All my data comes as a factor. Why all my data had been loaded as a factor.

I tried to use the packdge varhandle and use the function unfactor and transform everything in numeric vector using the lapply function, but didn't work.

##Choose a specifc set of cells
Data <- read.xlsx(Master_df, sheetName = "PLANILHA_FINAL", startRow = 3, 
endRow = 141, colIndex = 3:40, header = T)


#1th attempt 

Data <- as.numeric(unfactor(Data))
#2th attempt 
Data <- unfactor(Data)
Data <- as.numeric(Data)



Data[6:38] <- lapply(Data, as.numeric)
Data$GRUPO <- as.factor(Data$GRUPO)
Data$MOMENTO <- as.factor(Data$MOMENTO)
  • 1
    Possible duplicate of [How to convert a factor to integer\numeric without loss of information?](https://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-integer-numeric-without-loss-of-information) – pogibas Dec 14 '18 at 00:44
  • `readxl::read_excel` or `xlsx::read.xlsx2` might be worth trying to load the file and see what they return as column types. Alternatively they all have arguments to specify column type as well – NColl Dec 14 '18 at 01:00
  • Thank you NColl for your answer. Could you give me an idea what is the difference between use the formula readxl ::read_excel and readxl without the :: ? As you can see I new in R – Wellington Martins Dos Santos Dec 18 '18 at 00:58

1 Answers1

0

If it is all numeric then you can use this:

  Data[sapply(Data, is.factor)] <- lapply(Data[sapply(Data, is.factor)], as.character) %>% 
    lapply(Data[sapply(Data, is.character)], as.numeric)

Remember that you can't go straight from factor to numeric, you have to convert to character first.

morgan121
  • 2,213
  • 1
  • 15
  • 33