Multiple conversions

Sometimes we need to change the data type (class, mode) of a variable in R. There are various possible conversions, performed by functions like as.integer, as.factor or as.character. If we need to perform the same conversion on a number of variables (columns) in a data frame, we can convert them all simultaneously using the multConvert function, now included in the fuzzySim package (Barbosa, 2015).

multConvert <- function(data, conversion, cols = 1:ncol(data)) {
  for(i in cols) {
    data[ , i] <- conversion(data[ , i])

[presented with Pretty R]

By default it converts all the columns in the data frame, but you can specify just a few colums — for example:

mydata <- multConvert(data = mydata, conversion = as.integer, cols = c(2:4, 6, 8:11))

multConvert can also be used to apply other kinds of transformations. For example, if you need to divide some of your columns by 100, just write a function to do this and then use multConvert to apply this function to any group of columns:

div100 <- function(x) { x / 100 }
mydata <- multConvert(mydata, conversion = div100, cols = c(2, 4, 5))


Barbosa A.M. (2015) fuzzySim: applying fuzzy logic to binary similarity indices in ecology. Methods in Ecology and Evolution, 6: 853-858



Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s