我想修改这一行:
`with(EquityFundamentals, median(EquityFundamentals$Forward.P.E[EquityFundamentals$Industry == "Entertainment"], na.rm = "TRUE"))`
数据:
> 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))
答案 0 :(得分:0)
您可以这样做(不是最优雅的方式,但是可以)。
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=",")) )}
完成任务的方法有很多,包括by
,dplyr
,split
和其他几种方法,这些内容在this帖子中进行了全面介绍。