2

I have a list of data frames:

mylist<-list(df1=data.frame(Var1=c("A","b","c"), var2= 
c("a","b","c")), df2= data.frame(var1 = c("a","B","c"), 
VAr2=c("A","B","C")))

I would like to change all cases within the column headings and each element of a string to lowercase. (This way when I merge data frames all variables merge correctly and 'cat' vs "Cat' are not read as different entries).

The output would look like:

mylist<-list(df1=data.frame(var1=c("a","b","c"), var2= 
c("a","b","c")), df2= data.frame(var1 = c("a","b","c"), 
var2=c("a","b","c")))

I have tried the following:

cleandf <- lapply(mylist, function(x) tolower(mylist[x])
Danielle
  • 785
  • 7
  • 15

1 Answers1

1

Here is a similar approach to Masoud's answer

lapply(mylist, function(x) {
  names(x) <- tolower(names(x))
  x[] <- lapply(x, tolower)
  x
})
#$df1
#  var1 var2
#1    a    a
#2    b    b
#3    c    c

#$df2
#  var1 var2
#1    a    a
#2    b    b
#3    c    c

The first lapply iterates over your list. For each data frame - represented by the x - we first change its column names. The second lapply then applies tolower to each column of your data frames.

markus
  • 25,843
  • 5
  • 39
  • 58
  • I am getting an error. Could it be because some columns are factors and others characters? – Danielle Nov 02 '18 at 21:14
  • Mmh. Hard to tell without seeing your data. Can you update your question? (Don't believe it's a factor/character issue.) – markus Nov 02 '18 at 21:18
  • I know, I am afraid it is too much data (24.7 Mb) to attach. – Danielle Nov 02 '18 at 21:23
  • How many columns does each data frame have and how long is your list? A snippet might be enough to test, i.e. `dput(lapply(mylist[1:2], head, 3))`. – markus Nov 02 '18 at 21:24