0
df <- data.frame(class=c('A', 'B'),
                 var2=c(1, 0),
                 var3=c(0, 1))

for (i in colnames(df)[2:3]) {
  #print(i)
  table(paste0('df$', i), df$class)
}

results in

Error in table(paste0("df$", i), df$class) : 
  all arguments must have the same length

Also tried putting

get(paste0('df$',i))

Is there a way to loop through these columns and tabulate?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Log On
  • 69
  • 9
  • 2
    `paste0('df$',i)` creates a string, not an expression. One _could_ use `eval(parse(text=paste0('df$',i)))`, but that's a really bad idea in the long run, don't get used to doing things like that. I suggest instead in _your_ code to use `table(df[[i]], df$class)`. See https://stackoverflow.com/q/1169456/3358272; https://stackoverflow.com/q/18222286/3358272. – r2evans Feb 18 '23 at 23:31

2 Answers2

2

Not much info on what exactly your preferred output is other than it tabulates the columns, but here's a potential solution:

# This is your df:
class<- c('A','B')
var2<- c(1,0)
var3 <- c(0,1)
df<- data.frame(class,var2,var3)
head(df)

  class var2 var3
1     A    1    0
2     B    0    1

# Using lapply to tabulate each column. The output is a list of tables:
dftable <- lapply(df, table)

The output looks like this:

> dftb
$class

A B 
1 1 

$var2

0 1 
1 1 

$var3

0 1 
1 1 

The map() function from the purr package (part of tidyverse) can also be used:

library(purrr)
df|>
  map(table) # produces same output
Wael
  • 1,640
  • 1
  • 9
  • 20
2

The issue with your code is that because paste0() returns a character vector e.g, 'var2' and is not a correct argument for table() function. You can use the double bracket '[[' to extract the columns:

# create a list to save the results from loop
 tl<-vector(mode = 'list')
# run the loop and add the results for each column in the corresponding element of 'tl'

for (i in colnames(df)[2:3]) {
  tl[[i]]<-table(df[[i]], df$class)
}

output

tl

$var2
   
    A B
  0 0 1
  1 1 0

$var3
   
    A B
  0 1 0
  1 0 1

alternatively you can use lapply() function:

lapply(df[, 2:3], function(x) table(x, df$class))

var2
   
x   A B
  0 0 1
  1 1 0

$var3
   
x   A B
  0 1 0
  1 0 1
S-SHAAF
  • 1,863
  • 2
  • 5
  • 14