The code in the question is not working because:
- What is defined earlier in the code is a vector
columns
, not cols
;
- the loop index
i
will take each of the values in columns
, therefore index the data set mtcars
with it directly, mtcars[[i]]
extracts the appropriate column. See also Dynamically select data frame columns using $ and a vector of column names
In the code below I first create a results list with the same length as columns
and with its values as names. Then, in the for
loop, assign the tables to the list's members.
The two commented-out instructions do what the next one-liner does.
columns <- c("cyl", "vs")
# tbl_list <- vector("list", length = length(columns))
# names(tbl_list) <- columns
tbl_list <- setNames(vector("list", length = length(columns)), columns)
for (i in columns) {
tbl_list[[i]] <- table(mtcars[[i]])
}
tbl_list
#> $cyl
#>
#> 4 6 8
#> 11 7 14
#>
#> $vs
#>
#> 0 1
#> 18 14
Created on 2022-10-20 with reprex v2.0.2