Reputation: 15
I've recently started using R/RStudio to do analysis work and I've stumbled upon a problem where a for loop would help me cut down on a lot of repetitive tasks.
I have a project in which my next course of action is to use the names of several variables in my data set, to add more variables to the data set.
Here is what it would look like if I were to do it one name at a time:
#Create variable for if analyst got the game correct
master.set$Lee.Corso.RW <- ifelse(master.set$Lee.Corso == master.set$Winner, "Correct", "Incorrect")
I tried to do this for a series of names by creating lists and using the lists in a for loop like so:
Analyst.Names <- names(master.set[, 13:125])
names.length <- length(Analyst.Names)
An.Var.Names.RW <- paste(Analyst.Names[1:names.length], ".RW", sep = "")
for (i in 1: names.length){
#Create variable for if analyst got the game correct
master.set$An.Var.Names.RW[i] <- ifelse(master.set$Analyst.Names[i] == master.set$Winner, "Correct", "Incorrect")
}
When I run the for loop, I don't have any errors, but it doesn't do anything. The data set looks exactly the same. I'm hoping that the error I made is a small one. Does anyone know of a way I can accomplish this?
Thanks!
Upvotes: 1
Views: 140
Reputation: 887911
In the for
loop, the issue is that we are using $
to extract the values in the object
master.set$An.Var.Names.RW[i] <- ifelse(master.set$Analyst.Names[i] == master.set$Winner, "Correct", "Incorrect")
Instead it can be [[
master.set[[An.Var.Names.RW[i]]] <- ifelse(master.set[[Analyst.Names[i]]] == master.set$Winner, "Correct", "Incorrect")
Using a reproducible example
data(iris)
nm1 <- names(iris)[1:3]
for(i in seq_along(nm1)) print(head(iris)$nm1[i])
#NULL
#NULL
#NULL
And changing it to [[
for(i in seq_along(nm1)) print(head(iris)[[nm1[i]]])
#[1] 5.1 4.9 4.7 4.6 5.0 5.4
#[1] 3.5 3.0 3.2 3.1 3.6 3.9
#[1] 1.4 1.4 1.3 1.5 1.4 1.7
Difference is that in the first case, it is literally checking for a named nm1[i]
instead of the value stored in that object i.e. 'Sepal.Length', 'Sepal.Width', etc.
Upvotes: 1