An apply-type function for data frames.

dfapply(data, FUN, select = TRUE, ...)

Arguments

data

data frame

FUN

a function to apply to (some) variables in the data frame

select

a logical, character (naming variables), or numeric vector or a function used to select variables to which FUN is applied. If a function, it should take a vector as input and return a single logical. See examples.

...

arguments passed along to FUN

Examples

dfapply(iris, mean, select = is.numeric)
#> $Sepal.Length
#> [1] 5.843333
#> 
#> $Sepal.Width
#> [1] 3.057333
#> 
#> $Petal.Length
#> [1] 3.758
#> 
#> $Petal.Width
#> [1] 1.199333
#> 
dfapply(iris, mean, select = c(1,2))
#> $Sepal.Length
#> [1] 5.843333
#> 
#> $Sepal.Width
#> [1] 3.057333
#> 
dfapply(iris, mean, select = c("Sepal.Length", "Petal.Length"))
#> $Sepal.Length
#> [1] 5.843333
#> 
#> $Petal.Length
#> [1] 3.758
#> 
if (require(mosaicData)) {
  dfapply(HELPrct, table, select = is.factor)
  do.call(rbind, dfapply(HELPrct, mean, select = is.numeric))
}
#>                         [,1]
#> age               35.6534216
#> anysubstatus              NA
#> cesd              32.8476821
#> d1                 3.0596026
#> daysanysub                NA
#> dayslink                  NA
#> drugrisk                  NA
#> e2b                       NA
#> female             0.2362031
#> i1                17.9072848
#> i2                24.5474614
#> id               233.4017660
#> indtot            35.7284768
#> linkstatus                NA
#> mcs               31.6766783
#> pcs               48.0485416
#> pss_fr             6.7064018
#> sexrisk            4.6423841
#> avg_drinks        17.9072848
#> max_drinks        24.5474614
#> hospitalizations   3.0596026