1

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.

Glu
  • 327
  • 3
  • 14
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. Also you should show your code attempt and describe exactly what "didn't work." – MrFlick Sep 05 '19 at 15:16
  • THank you for your comment MrFlick. I usually do post my code attempts. This time I didn't because I thought that maybe other people had better ways of doing it, like with dplyr or something like that...Will do it next time. – Glu Sep 05 '19 at 15:32

1 Answers1

2

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • That worked perfectly, thank you. That's what I was trying to do based on what I found on a previous post but I was indeed trying data$v, that's why it was not working. – Glu Sep 05 '19 at 15:30
  • Do you mind if I ask another question? I am also trying something different, like: for(v in my_vars) { shapiro.test(data[[v]]) } but it is not working. I also tried: shapResult = matrix(6,1) for(v in my_vars) { shapResult[v] = shapiro.test(data[[v]]) } – Glu Sep 05 '19 at 15:50
  • What does "not working" mean exactly? The same looping technique should work. If it doesn't, you can start a new post with a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that shows exactly what the problem is. – MrFlick Sep 05 '19 at 15:51