Home > OS >  How to feed a vector of column names to the table function
How to feed a vector of column names to the table function

Time:10-20

Example data:

mtcars <- mtcars
cols <- c("cyl", "vs")

# I would like to create a table for each column in `columns`:

for (i in seq(cols)) {
  print(table(mtcars$cols[i]))
}

# I also tried:
for (i in seq(cols)) {
  print(table(get(paste0("mtcars$", cols[i]))))
}

But this does not produce any table. How can I feed a vector of column names to the table function?

CodePudding user response:

What about this?

> lapply(mtcars[cols], table)
$cyl

 4  6  8
11  7 14

$vs

 0  1
18 14

or using mget

> with(mtcars, lapply(mget(cols), table))
$cyl

 4  6  8
11  7 14

$vs

 0  1
18 14

> lapply(mget(columns, as.environment(mtcars)), table)
$cyl

 4  6  8
11  7 14

$vs

 0  1
18 14

CodePudding user response:

The code in the question is not working because:

  1. What is defined earlier in the code is a vector columns, not cols;
  2. 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

  • Related