简体   繁体   中英

Create R Function with flexibility to reference different datasets

I am trying to create a simple function in R that can reference multiple datasets and multiple variable names. Using the following code, I get an error, which I believe is due to referencing:

set.seed(123)
dat1 <- data.frame(x = sample(10), y = sample(10), z = sample(10))
dat2 <- data.frame(x = sample(10), y = sample(10), z = sample(10))

table(dat1$x, dat1$y)
table(dat2$x, dat2$y)

fun <- function(dat, sig, range){print(table(dat$sig, dat$range))}

fun(dat = dat1, sig = x, range =  y)
fun(dat = dat2, sig = x, range =  y)

Any idea how to adjust this code so that it can return the table appropriately?

The [[ ]] operator on data frame is similar to $ but allows you to introduce an object and look for it's value. Then outside of the function you assign " x " value to sig . if you don't put quotes there R will look for x object

fun <- function(dat, sig, range){print(table(dat[[sig]], dat[[range]]))}

fun(dat = dat1, sig = "x", range =  "y")
fun(dat = dat2, sig = "x", range =  "y")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM