David Z
David Z

Reputation: 7051

loops for a list of dataframes

I have a similar situation like this:

    data1<-data.frame(a=c(1,2),b=c(3,4))
    data2<-data.frame(a=c(5,6),b=c(7,8))

    for(df in list(data1, data2)){
       df[,"a"]<-as.character(df[,"a"])
    }
    mode(data1$a)
    [1] "numeric"

I'm wondering why the loop failed to change the mode of the common variable a? and how to realize it?

Upvotes: 1

Views: 66

Answers (1)

Roland
Roland

Reputation: 132969

You are assigning to a temporary copy. The canonical way to do this:

mylist <- list(data1, data2)
mylist <- lapply(mylist, function(df) {
  df$a <- as.character(df$a) 
  df})
mode(mylist[[1]]$a)
#[1] "character"

If you insist on a for loop:

mylist <- list(data1, data2)
for(i in seq_along(mylist)){
  mylist[[i]]$a <- as.character(mylist[[i]]$a)
}
mode(mylist[[1]]$a)
#[1] "character"

Upvotes: 1

Related Questions