Reputation: 233
I'm trying to convert few column of a data frame from char to numeric in R.
Exemple:
transform_function <- function(dataframe, vector){
for (i in vector){
dataframe[[i]] <- as.numeric(dataframe[[i]])
}
return(dataframe)
}
where my data frame has columns from a to z and I do this:
vector <- c("a", "c", "d", "h")
transform_function(dataframe, vector)
Getting the follow error:
Error in `[[<-.data.frame`(`*tmp*`, i, value = numeric(0)) :
replacement has 0 rows, data has 11068
4.
stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N, nrows), domain = NA)
3.
`[[<-.data.frame`(`*tmp*`, i, value = numeric(0))
2.
`[[<-`(`*tmp*`, i, value = numeric(0))
1.
transform_function(dataframe, vector)
Upvotes: 1
Views: 1244
Reputation: 2764
Most efficient way:
cols_to_convert <- colnames(dt)
data.table::setDT(dt)[, (cols_to_convert) := lapply(.SD, as.numeric), .SDcols = cols_to_convert ]
Upvotes: 0
Reputation: 28695
You can use dplyr::mutate_at
.
library(dplyr)
to_change <- c('a', 'c')
df <- data.frame(a = as.character(1:10), b = as.character(11:20), c = as.character(21:30))
df %>% mutate_at(to_change, as.numeric)
Upvotes: 1
Reputation: 9763
Try using apply to iterate over the columns rather than writing your own function. Example solution:
df <- data.frame(c("a", "c", "d", "h"),c(1,2,3,4))
df<-apply(df,2,as.numeric)
df
Upvotes: 1