1

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) 

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

You know this wont work right?. eg if df <- data.frame(c("a", "c", "d", "h"),c(1,2,3,4),stringsAsFactors = F) then this code will fail
0

Most efficient way:

 cols_to_convert <- colnames(dt)
 data.table::setDT(dt)[, (cols_to_convert) := lapply(.SD, as.numeric), .SDcols = cols_to_convert ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.