For loop over the same variable in multiple datasets


This Content is from Stack Overflow. Question asked by wilsonmking

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

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?


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?