0

I have 7 dataframes where the first variable is just a list of the 50 states. The problem is that in some of them, the states are all capitals, all lower case or mixed. Instead of writing 7 different tolower() commands, I was wondering if there is a way to do this using a loop or lapply()?

I've tried these two ways and neither worked:

ivs <- c("taxes","urban","gini","educ","inc","cong"))## a character vector of the data frame names

for (i in length(1:ivs)){
    i$state <- tolower(i$state)
}

and this way:

ivs <- c("taxes","urban","gini","educ","inc","cong"))


sapply(ivs, function(x) {
   x$state <- tolower(x$state)
   })

Thanks for the help!

ModalBro
  • 544
  • 5
  • 25

4 Answers4

0

Try this out if you want to use a for loop

ivs <- list(taxes,urban,gini,educ,inc,cong))## Put your dataframes into a list

for (i in ivs){
    i$state <- tolower(i$state)
}
C_Z_
  • 7,427
  • 5
  • 44
  • 81
0

You could put apply within lapply

Example:

l <-
  list(
data.frame(state = c("ARIZONA", "teXaS")),
data.frame(state = c("arizona", "TEXAS")),
data.frame(state = c("AriZonA", "TEXaS"))
  )

lapply(l, function(x) apply(x[1], 2, tolower))


#[[1]]
#     state    
#[1,] "arizona"
#[2,] "texas"  
#
#[[2]]
#     state    
#[1,] "arizona"
#[2,] "texas"  
#
#[[3]]
#     state   
#[1,] "arizona"
#[2,] "texas"
jalapic
  • 13,792
  • 8
  • 57
  • 87
0

You could try something like:

for( v in ivs){
  eval(parse(text=paste0(v,"$state <- tolower(",v,"$state)")))
}
Marco Torchiano
  • 712
  • 7
  • 21
  • 1
    @stanO you *could* try it. you *should not* try it – rawr Feb 12 '15 at 21:25
  • You should be aware of the [dangers of eval(parse())](http://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse). There are almost always more "R-like" ways to do things like this. – MrFlick Feb 12 '15 at 21:35
  • agreed: this is not the most R-like way of solving the original problem. I proposed it because it is the closest to the original post idea of looping on the data frames names. – Marco Torchiano Feb 13 '15 at 17:41
  • 1
    @MTk using `get` would be just as close or closer and would be far more palatable – eddi Feb 17 '15 at 15:33
  • The problem with `get()` is that it does not support `<-` e.g. `x=c(1,2,3);get("x")[1]<-0` gives a _target of assignment expands to non-language object_ – Marco Torchiano Feb 18 '15 at 09:34
0
lapply(dflist, function(df) {
    df[[1]] <- tolower(df[[1]])
    df
})
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187