0

In R I have 20 different datasets which all contain the same variables. data1999, data2000, ... data2018.

The data contains stocks with some ratios. Right now I want to sort these stocks based on 2 criteria.

First I want to take the first 2 deciles of a certain variable which is called TVDecile, of this cheapest 2 deciles, I want to select the 30 stocks which rank the best based on the variable Momentum.

So for example:

data199$TVDecile <- c(1,8,3,5,6,2) data1999$momentum <- c(0.2 , -0.5, 0.4, 0.1, 0.6, 0.3)

What I then need to do is first filter on data1999$TVDecile. I only need the first 2 deciles (so numbers 1 and 2). I could maybe do this with an If statement?

After that I want to sort the remaining numbers by momentum. So the one with the momentum of 0.3 should come first in the list and the one with the momentum of 0.2 should come second. A new variable should be created which contains these 2 values.

  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 16 '20 at 16:18
  • Maybe [this](https://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-multiple-columns) can help. – Rui Barradas Mar 16 '20 at 16:28
  • Can you post sample data? Please edit **the question** with the output of `dput(data1999)`. Or, if it is too big with the output of `dput(head(data1999, 20))`. – Rui Barradas Mar 16 '20 at 16:29
  • @MrFlick Is it more clear now? – Pieter Slegers Mar 16 '20 at 17:36
  • It sounds like you want to first sort/arrange by `TVDecile` first, then filter the first two rows only, then sort/arrange by `momentum`. What did you want in the end? Your whole `data1999` dataset with stocks sorted in this way, with 2 rows in the end? Or did you just want a vector of length 2 with the values of momentum (in this case was .3 and .2)? How would you use this new "variable" with 2 values? – Ben Mar 16 '20 at 22:14

0 Answers0