Reputation: 663
I have a dataframe called covars with three ethnicities. How do I apply function Get_STATs
so I can get the output for each ethnicity?
Right, now I am running it like this:
tt <- covars[covars$ETHNICITY == "HISPANIC",]
Get_STATs(tt)
tt <- covars[covars$ETHNICITY == "WHITE",]
Get_STATs(tt)
tt <- covars[covars$ETHNICITY == "ASIAN",]
Get_STATs(tt)
I tried to run it like this
aggregate(covars, by = list(covars$ETHNICITY), FUN = Get_STATs)
which generates error rror: $ operator is invalid for atomic vectors
Upvotes: 0
Views: 193
Reputation: 95
Depending on the Get_STATs function, you can use dplyr:
tt <-
covars %>%
group_by(ETHNICITY) %>%
Get_STATs()
Upvotes: 0
Reputation: 886938
aggregate
runs on each column separately, we may need by
do.call(rbind, by(covars, covars$ETHNICITY, FUN = Get_STATs))
Or split
into a list
and loop over the list
and apply the function
do.call(rbind, lapply(split(covars, covars$ETHNICITY), Get_STATs))
If we need the ETHNICITY names as well
lst1 <- split(covars, covars$ETHNICITY)
do.call(rbind, Map(cbind, ETHNICITY = names(lst1), lapply(lst1, Get_STATs)))
Upvotes: 1