[R] Converting character to numeric using the package "XLConnect"
Nelly Reduan
nell.redu at hotmail.fr
Wed Aug 30 21:24:25 CEST 2017
Hello,
>From an Excel file imported into R where each cell contains characters, I would like to convert some characters to numeric. However, my code doesn’t work. When I write data to worksheets in an Excel file, some numbers in the cells are stored as text (instead of numeric). Here is my code (the Excel file is attached):
rm(list=ls(all=TRUE))
library(XLConnect)
tab <- loadWorkbook("C:/Users/Downloads/File.xlsx", create = TRUE)
set <- readWorksheet(tab, sheet = "settings")
setNum <- readWorksheet(tab, sheet = "settings", colTypes="numeric")
index <- which((!is.na(setNum)), arr.ind=TRUE)
if(length(index)!=0){
set[index] <- unlist(lapply(set[index], function(x) as.numeric(as.character(x))))
}
## to check
set[10,1] ## Problem: must be numeric !!!!
writeWorksheetToFile("C:/Users/Downloads/Test.xlsx", data=set, sheet="settings", styleAction = XLC$"STYLE_ACTION.NONE")
How can I convert the numbers which are stored as characters to numeric?
Thanks so much for your time.
Have a nice day
Nell
More information about the R-help
mailing list