Repeat calculation over variables with same root

Viewed 42

This is a toy dataframe:

mydata<-structure(list(katz1 = c(1, 1, 1, 0, 1, 1, 1, 1, 1, 0), katz2 = c(1,
1, 1, 1, 1, 1, 1, 1, 1, 1), katz3 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), row.names = c(NA, 10L),
class = c("tbl_df", "tbl", "data.frame" ))

I want to get a table for each katz variable with a loop. This has not worked:

for (i in 1:3) 
{
  item<-paste0("mydata","$","katz",i)
  table(item,useNA="ifany")
}

It creates the item, but table is not applied to it.

What is wrong?

Thank you.

1 Answers

Rather use just the column name for subsetting in brackets.

for (i in 1:3) {
  item <- paste0("katz", i)
  print(table(mydata[, item], useNA="ifany"))
}

Or, to avoid for loops use grepl in an lapply. This identifies columns containing "katz" in its names and applies table on them.

lapply(mydata[grepl("katz", names(mydata))], table, useNA="ifany")
Related