0

I would like to modify this line:

`with(EquityFundamentals, median(EquityFundamentals$Forward.P.E[EquityFundamentals$Industry == "Entertainment"], na.rm = "TRUE"))`
  • to use a list of names, not just "Entertainment"
  • The list of names is characters in a vector called "Sectors"
  • The output would be:
    • new values for every sector (e.g. a median for every sector; MedianEnergy, MedianTech, etc.) OR
    • a data frame with the Sector in column 1 and Median in column 2

Data:

> EquityFundamentals
  Sector.Title. Forward_P.E.Title.
1        Energy                6.7
2        Energy                7.5
3          Tech               10.4
4          Tech               11.5

structure(list(
  Sector.Title. = structure(c(1L,1L,2L,2L),
    .Label = c("Energy","Tech"), class = "factor"),
  Forward_P.E.Title. = c(6.7,7.5,10.4,11.5)),
  .Names = c("Sector.Title.", "Forward_P.E.Title."
), class = "data.frame", row.names = c(NA, -4L))
smci
  • 32,567
  • 20
  • 113
  • 146
dwdionis
  • 83
  • 7
  • 1
    Could you add a sample of your data? Makes it easier to answer. – Hector Haffenden Mar 14 '19 at 21:04
  • Hi - I did a basic edit to show how it's laid out. Is that sufficient? – dwdionis Mar 14 '19 at 21:08
  • 1
    Are you able to use dput() on your data (or a small subsection of it), then paste that into your question? – Hector Haffenden Mar 14 '19 at 21:09
  • Does a screenshot help? https://i.imgur.com/x7LdzXZ.png – dwdionis Mar 14 '19 at 21:16
  • 1
    Hi, screenshots tend not to be to helpful, see https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for how to make a good example. – Hector Haffenden Mar 14 '19 at 21:17
  • 3
    You probably want something like `aggregate(Forward.P.E ~ Industry, EquityFundamentals, median)` - there are many similar questions on this site. Perhaps take a look [here](https://stackoverflow.com/questions/11562656/calculate-the-mean-by-group). – Ritchie Sacramento Mar 14 '19 at 21:23
  • H 1 you nailed it. Elegant and the way I was hoping it would work. I knew it was an easy task for a guru. :) – dwdionis Mar 15 '19 at 19:21
  • 1
    Possible duplicate of [Calculate the mean by group](https://stackoverflow.com/questions/11562656/calculate-the-mean-by-group) – camille Mar 15 '19 at 22:06

1 Answers1

0

You can do it like this (not the most elegant way, but works).

Sectors <- c("Entertainment", "Energy", "Tech")
for (i in 1:length(Sectors)){with(EquityFundamentals, print(paste((Sectors[i]), median(EquityFundamentals$Forward.P.E[EquityFundamentals$Industry==(Sectors[i])], na.rm = "TRUE"), sep=",")) )}

There are many ways to do the task, including by, dplyr, split and several others, which are comprehensively described in this post.

Oka
  • 1,318
  • 6
  • 11