0

I am relatively new to R. I just started learning it and am really impressed. I have a few questions that I would like to ask. Say I have a data frame as such:

ISIN     sector
12345    Technology
34567    Utilities
45256    Financials
52000    Technology
33662    Financials

I want to break my data down into sectors. Such as how many securities have div yields so on and so forth. How can I group them by sector? Is there a way by which this can be done in R.

AAlferez
  • 1,480
  • 1
  • 22
  • 48
Rambo223
  • 5
  • 3
  • Welcome to Stack Overflow! Could you give us a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – Jaap Feb 26 '14 at 21:42

2 Answers2

0

You can subset data frames using conditions on the rows in R:

FinancialsData <- myDataFrame[myDataFrame$sector == "Utilities", ]

If you want to break it up into several data frames, one for each sector, you can use the split function:

splitData <- split(myDataFrame, f = myDataFrame$sector)

which yields a list where each element is each specific sector.

Christopher Louden
  • 7,540
  • 2
  • 26
  • 29
0

You can also use the plyr package to summarize your data by sector.

newDF <- ddply(myDF, .(sector), summarise, #some code to create summary variables)

As you did not provide a reproducable example, it is hard to give a good answer as we can't see the structure of your data. However, below an example of how your code might look like:

# creating a data.frame
myDF <- read.table(text="ISIN     sector   div.yield
12345    Technology    3
34567    Utilities     4
45256    Financials    1
52000    Technology    5
33662    Financials    2", header = TRUE, strip.white = TRUE)

# summarising the data.frame
newDF <- ddply(myDF, .(sector), summarise, n.yield = as.numeric(length(div.yield)), 
                av.yield = round(mean(div.yield),2), 
                ISIN.string = paste(as.character(ISIN), collapse = ",") 
)
Community
  • 1
  • 1
Jaap
  • 81,064
  • 34
  • 182
  • 193