I have multiple datasets and would like to create a contingency table for the same variable in each of them. I am attempting to write a for loop over these datasets, but am having difficulty accessing the necessary variable. Here's a fake set-up to illustrate my issue:
data1 <- data.frame(name = c("A", "B", "C"),
value1 = c(1, 2, 2),
value2 = c(1, 3, 7))
data2 <- data.frame(name = c("D", "E", "F"),
value1 = c(3, 4, 3),
value2 = c(8, 2, 1))
datasets <- c("data1", "data2")
If I manually execute table(data1$value1) then I receive a result. However, if I try something like the following:
for (i in seq_along(datasets)) {
variable <- datasets[[i]]$value1
table(variable)
}
then R throws an error message "Error: $ operator is invalid for atomic vectors." Given this, what is the best way to achieve my initial aim?