Using with( ) and by( )

There are two functions that can help write simpler and more efficient code.


The with( ) function applys an expression to a dataset. It is similar to DATA= in SAS.

# with(data, expression)
# example applying a t-test to a data frame mydata

with(mydata, t.test(y ~ group))


The by( ) function applys a function to each level of a factor or factors. It is similar to BY processing in SAS.

# by(data, factorlist, function)
# example obtain variable means separately for
# each level of byvar in data frame mydata
by(mydata, mydata$byvar, function(x) mean(x))

To Practice

Take the Data Manipulation with R Course to gain a thorough understanding of how to work extract value from data in R.