Cisco
Cisco

Reputation: 137

Why this loop in not working?

I have different data frames with the same number and column names. I want to transform the same variable in all dfm from character to factor. I tried to do it like the following without success.

#different data frames:
names<-c("fa.7","fa.8","fa.9","fa.10","fa.11","fa.12","fa.13","fa.14","fa.15","fa.16","fa.18","fa.19","fa.20","fa.22","fa.28","fa.30","fa.32","fa.33","fa.36","fa.38","fa.39","fa.42","fa.43","fa.45","fa.47","fa.48","fa.52","fa.53","fa.54","fa.55","fa.56","fa.58","fa.59","fa.60","fa.63")

#Now I try to transform into a factor one column in all data frames.
for (i in names){
  df<-get(i)
  df$IID=as.factor(df$IID)
  assign(names[i],df)
}

What Im doing wrong?

Upvotes: 0

Views: 62

Answers (2)

Grammilo
Grammilo

Reputation: 1369

Looks like you are trying to assign data type factor to elements of a vector which initially were characters. Am I right? If that's the case, below piece of code does it in a very simple way. Kindly let me know if it answers your question.

names<-c("fa.7","fa.8","fa.9","fa.10","fa.11","fa.12","fa.13","fa.14","fa.15","fa.16","fa.18","fa.19","fa.20","fa.22","fa.28","fa.30","fa.32","fa.33","fa.36","fa.38","fa.39","fa.42","fa.43","fa.45","fa.47","fa.48","fa.52","fa.53","fa.54","fa.55","fa.56","fa.58","fa.59","fa.60","fa.63")
str(names)
df<-lapply(names,factor)
str(df)

Upvotes: 0

C-x C-c
C-x C-c

Reputation: 1311

You need to use assign(i, df) not assign(names[i], df).

Although, there are much better ways to do this, where you can avoid a for loop. For instance, use lapply:

dfs <- list(fa.7,fa.8)
listFactorDFs <- lapply(
  dfs,
 function(i){
    i$IID <- as.factor(i$IID)
    i
  }
)

Upvotes: 1

Related Questions