1

I'm trying to write a function that will allow me to change the case of certain fields in my data frame to lowercase. I'm trying to do this by using the function, for, and tolower commands, but I'm not having any luck. I'm still fairly new to R, so I might be missing something obvious. I would appreciate any help anyone can provide.

standardize_lowercase <- function(df, objs) {
  for(i in 1:length(objs)) {
    df[i] <- tolower(df[i])
  }
}

I'm using df to refer to my main data frame, and objs would be a character vector with the names of the fields from the data frame I would like to convert to lowercase.

www
  • 38,575
  • 12
  • 48
  • 84
CPG
  • 17
  • 4
  • 1
    Any values you change of a data.frame inside a function will not be visible outside a function. (R act more like pass-by-value than pass-by-reference). You would need to return the updated data.frame and re-assign to either the same variable or a new one. See https://stackoverflow.com/questions/3969852/update-data-frame-via-function-doesnt-work (but ignore the "assign" option - that's poor R style). – MrFlick Aug 10 '18 at 19:46

1 Answers1

2

We can use the dplyr package as follows. Provide the column names as a string and tolower to the mutate_at function.

library(dplyr)

# Create example data frame
dat <- data_frame(A = c("A", "B", "C"),
                  B = c("A", "B", "C"),
                  C = c("A", "B", "C"),
                  D = c("A", "B", "C"),
                  E = c("A", "B", "C"))

# Assuming that we want to change the column B, C, E to lower case
obj <- c("B", "C", "E")

dat2 <- dat %>%
  mutate_at(vars(obj), funs(tolower(.)))
dat2
# # A tibble: 3 x 5
#   A     B     C     D     E    
#   <chr> <chr> <chr> <chr> <chr>
# 1 A     a     a     A     a    
# 2 B     b     b     B     b    
# 3 C     c     c     C     c 

Or here is a base R solution using lapply.

dat[obj] <- lapply(dat[obj], tolower)
dat
# # A tibble: 3 x 5
#   A     B     C     D     E    
#   <chr> <chr> <chr> <chr> <chr>
# 1 A     a     a     A     a    
# 2 B     b     b     B     b    
# 3 C     c     c     C     c

Here is an example to convert the second option to a function.

dat_tolower <- function(data, target){
  data[target] <- lapply(data[target], tolower)
  return(data)
}

dat_tolower(dat, target = obj)
# # A tibble: 3 x 5
#   A     B     C     D     E    
#   <chr> <chr> <chr> <chr> <chr>
# 1 A     a     a     A     a    
# 2 B     b     b     B     b    
# 3 C     c     c     C     c 
www
  • 38,575
  • 12
  • 48
  • 84