Y.P Y.P - 9 months ago 40
R Question

Apply function only if columns respect condition

I’m new to R and I’m trying to learn fundamentals. I’m facing a small problem for which I can’t find a solution online.

What I want to do: write a function to lower case for all the columns in my

data.frame
if they respect a condition
(class = factor)


This code works, but for all my columns :

lower = function(x) { data.frame(tolower(as.matrix(x))) }


I need more something like this, but it doesn’t work:

lower = function (x) {
for (i in 1:length(x)) {
if (class(i)=="factor") {
data.frame(tolower(as.matrix(x)))
}
}
}


x
is my
data.frame
.

Answer Source

Your attempt is close, but the returning is the tricky part. Since there is no sample data, here is an example using iris and changing to upper case instead:

as.data.frame(lapply(head(iris), function(x){
  if(class(x) == "factor"){
    return(toupper(x))
  } else{
    return(x)
  }
}))

lapply is an efficient way to loop through list data (and a data.frame is inherently a list). as.data.frame is necessary to convert back to a data.frame.

However, there are even better tools available to avoid writing them yourself, including mutate_if from dplyr:

head(iris) %>%
  mutate_if(is.factor, toupper)

Both of these return:

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  SETOSA
2          4.9         3.0          1.4         0.2  SETOSA
3          4.7         3.2          1.3         0.2  SETOSA
4          4.6         3.1          1.5         0.2  SETOSA
5          5.0         3.6          1.4         0.2  SETOSA
6          5.4         3.9          1.7         0.4  SETOSA