I have a simple loop that iterate across a number of string values in a vector called measurements:
measurements <- c("A","B","C","D")
here a reproducible data frame:
value <- c(1,2,3,4)
measurement <- c("A","B","C","D")
questiondata <- data.frame(measurement, value)
questiondata <- as.tibble(questiondata)
At first, the loop filters rows based on the measurement column. If the variable assigned in the loop has the same name as the column name of my data frame the filter does not work, it prints the entire dataframe 4 times:
for (measurement in measurements){
print(measurement)
print(questiondata %>% dplyr::filter(measurement == measurement))
}
If, instead,I change the variable name - from "measurement" to "m" for instance- it works:
for (m in measurements){
print(m)
print(questiondata %>% dplyr::filter(measurement == m))
}
Does anyone know the reason of this behaviour?
measurement in measurement
should work (since in your reproducible code you use measurement and not measurements), even though you should consider a different naming ;) - Julianmeasurement in measurements
as the vector measurements is assigned before. - spleen