0

I would like an easier way to do what this does

MEAN1 = mean(CIS2017$USHRWK[CIS2017$AGE == 1 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN2 = mean(CIS2017$USHRWK[CIS2017$AGE == 2 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN3 = mean(CIS2017$USHRWK[CIS2017$AGE == 3 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN4 = mean(CIS2017$USHRWK[CIS2017$AGE == 4 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN5 = mean(CIS2017$USHRWK[CIS2017$AGE == 5 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN6 = mean(CIS2017$USHRWK[CIS2017$AGE == 6 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN7 = mean(CIS2017$USHRWK[CIS2017$AGE == 7 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN8 = mean(CIS2017$USHRWK[CIS2017$AGE == 8 | CIS2017$ALFST == 1], na.rm = TRUE)  
MEAN9 = mean(CIS2017$USHRWK[CIS2017$AGE == 9 | CIS2017$ALFST == 1], na.rm = TRUE)  

Doing the following doesn't seem to work

AGE_GROUPS = seq(1, 16, 1)  
MEAN = mean(CIS2017$USHRWK[CIS2017$AGE == AGE_GROUPS | CIS2017$ALFSTN == 1], na.rm = TRUE)
M--
  • 25,431
  • 8
  • 61
  • 93
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data so we can run your code – camille Jan 28 '20 at 21:57
  • Try `sapply(AGE_GROUPS, function(x) mean(CIS2017$USHRWK[CIS2017$AGE == x | CIS2017$ALFST == 1], na.rm = TRUE))` – markus Jan 28 '20 at 21:57
  • Matt, as a "best practice", it might be more useful to you do store the means in a named-list or named-vector instead of individual variables. For instance, ThomasIsCoding's answer converts a names list to individual variables in your global environment, but if you remove the `list2env` and `envir=` from it, you will have a list of things you can work on. From there, using `sapply` or `lapply` functions (or their kin), it's easy to apply a single function or command-sequence to all of the means in one motion. – r2evans Jan 28 '20 at 22:00

1 Answers1

0

Maybe this is what you are after

list2env(setNames(
  lapply(AGE_GROUPS,
       function(k) mean(CIS2017$USHRWK[CIS2017$AGE == k | CIS2017$ALFSTN == 1], na.rm = TRUE)),
  paste("MEAN",AGE_GROUPS)),envir = .GlobalEnv)

or

v <- setNames(
  sapply(AGE_GROUPS,
       function(k) mean(CIS2017$USHRWK[CIS2017$AGE == k | CIS2017$ALFSTN == 1], na.rm = TRUE)),
  paste("MEAN",AGE_GROUPS))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81