Glu
Glu

Reputation: 327

Loop over variables in R

I am doing analysis in a very repetitive way. This is an example of what I am doing:

par(mfcol=c(1,1))
hist(data$dPrime, probability = T, main="dPrime",xlab="")
lines(density(data$dPrime),col=2)

# Score
hist(data$Score, probability = T, main="Score",xlab="")
lines(density(data$Score),col=2)

# Score2
hist(data$Score2, probability = T, main="Score2",xlab="")
lines(density(data$Score2),col=2)

# Confidence
hist(data$Confidence, probability = T, main="Confidence",xlab="")
lines(density(data$Confidence),col=2)

I am doing the same also for different types of analysis. How can I do this in a loop? I tried something that I saw from previous posts but it is not working. Any suggestion is appreciated.

Thank you everyone.

Upvotes: 1

Views: 53

Answers (1)

MrFlick
MrFlick

Reputation: 206232

You can just write a loop to iterate over your variables of interest.

my_vars <- c("dPrime", "Score", "Score2", "Confidence")

par(mfcol=c(1,1))
for(v in my_vars) {
  hist(data[[v]], probability = TRUE, main=v, xlab="")
  lines(density(data[[v]]), col=2)
}

Just be sure to use data[[v]] rather than data$v because you can't really use character variables with the $ operator. You need to use the more generic subsetting.

Upvotes: 2

Related Questions