CptNemo
CptNemo

Reputation: 6755

Accessing dataframe from variable name in xtabs

The problem is quite simple. I want to build crosstabs through the xtabs function. I also want to pass to the xtabs function the argument data= in the form of a string pulled out of a vector.

Consider the following MWE

dataframe_names <- c("DF1","DF2","DF3")
DF1 <- as.data.frame(UCBAdmissions)
xtabs(Freq ~ Gender + Admit, data=DF1)
# Admit
# Gender   Admitted Rejected
# Male       1198     1493
# Female      557     1278
dataframe_names[1]
# [1] "DF1"
xtabs(Freq ~ Gender + Admit, data=dataframe_names[1])
# Error in eval(predvars, data, env) : 
#   invalid 'envir' argument of type 'character'

How should I pass the argument?

Upvotes: 1

Views: 370

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You need to use get:

xtabs(Freq ~ Gender + Admit, data=get(dataframe_names[1]))
#         Admit
# Gender   Admitted Rejected
#   Male       1198     1493
#   Female      557     1278

Upvotes: 1

Related Questions