I have a dataframe with a bunch of columns that I need to convert to the numeric type. I have written the following code to try to do this, however it is saying the replacem
As SenorO pointed out, the reason your original code does not work is that $i
will not evaluate i
to find out it's current value. You should instead access and assign to the column using double brackets, which work when i
is a name or index number:
for (i in instanceconvert)
{
regmodel[[i]] <- as.numeric(regmodel[[i]])
}
Following Ari's approach, you can get rid of the loop:
regmodel[,instanceconvert] <-
lapply(regmodel[,instanceconvert,drop=FALSE],as.numeric)
You could also do this with your range, 7:262, in place of "instanceconvert", since you can access/assign by name or column number.
Just pass the columns you want as a data frame d
into the following:
data.frame(apply(d, 2, as.numeric))
This goes column by column and converts each into a numeric. Then just change your row-names and column-names accordingly.
You can use sapply for this:
dat <- sapply( dat, as.numeric )
If not every column needs converting:
library( taRifx )
dat <- japply( dat, which(sapply(dat, class)=="character"), as.numeric )
A fast a dirty way to do it, especially if you have variables all over that need converting, which would mean a lot of conversion code is to write the file out and read it back in again using something like write.csv/read.csv
write.csv(regmodel, file="regmodel.csv")
read.csv(file="regmodel.csv")
Here is quick solution from other question:
df[] <- lapply(df, function(x) as.numeric(as.character(x)))
Reference: Change all columns from factor to numeric in R
Combining the answer by @Andrii with the comment by @RobertYi, my short suggestion is
df[] <- sapply(df, as.numeric)
This ensures that the result stays as data frame.