Filter stock data

Hello everyone,
I am very grateful if anyone can help.
My data have 600 stockcodes, saved as "allstock.csv". I want to extract 100 stockcodes in file "selectstock.csv" which then contain all data in file allstock.csv.

For example: file "allstock.csv" is something like that

stockcode offerprice openprice closeprice openoffer closeopen
AAA 48.7 51 48.7 1.047227926 0.954901961
AAM 38 45.6 45.6 1.2 1
ABT 90 90 90 1 1
ACB 130.2 120 135 0.921658986 1.125
ACC 25 28.5 28.5 1.14 1
ACL 81 81 81 1 1
ACM 10.5 11.6 10.5 1.104761905 0.905172414
ADC 10.8 16.5 11.3 1.527777778 0.684848485
ADS 17 18 13.7 1.058823529 0.761111111
AGF 30 30 30 1 1
AGM 20 16 20.2 0.8 1.2625

And "selectstock.csv"

stock
AAA
ACC
ADS
AGM

I would like to get new file like that.

stockcode offerprice openprice closeprice openoffer closeopen
AAA 48.7 51 48.7 1.047227926 0.954901961
ACC 25 28.5 28.5 1.14 1
ADS 17 18 13.7 1.058823529 0.761111111
AGM 20 16 20.2 0.8 1.2625

Thank you in advance.

This is one way to do it using dplyr
Note: Please make your questions providing a REPRoducible EXample (reprex) like the following.

library(dplyr)

# Sample data
stocks <- data.frame(stringsAsFactors=FALSE,
    stockcode = c("AAA", "AAM", "ABT", "ACB", "ACC", "ACL", "ACM", "ADC",
                  "ADS", "AGF", "AGM"),
   offerprice = c(48.7, 38, 90, 130.2, 25, 81, 10.5, 10.8, 17, 30, 20),
    openprice = c(51, 45.6, 90, 120, 28.5, 81, 11.6, 16.5, 18, 30, 16),
   closeprice = c(48.7, 45.6, 90, 135, 28.5, 81, 10.5, 11.3, 13.7, 30, 20.2),
    openoffer = c(1.047227926, 1.2, 1, 0.921658986, 1.14, 1, 1.104761905,
                  1.527777778, 1.058823529, 1, 0.8),
    closeopen = c(0.954901961, 1, 1, 1.125, 1, 1, 0.905172414, 0.684848485,
                  0.761111111, 1, 1.2625)
)

selected_stocks <- c("AAA", "ACC", "ADS", "AGM")

stocks %>% 
    filter(stockcode %in% selected_stocks)
#>   stockcode offerprice openprice closeprice openoffer closeopen
#> 1       AAA       48.7      51.0       48.7  1.047228 0.9549020
#> 2       ACC       25.0      28.5       28.5  1.140000 1.0000000
#> 3       ADS       17.0      18.0       13.7  1.058824 0.7611111
#> 4       AGM       20.0      16.0       20.2  0.800000 1.2625000

Created on 2019-07-25 by the reprex package (v0.3.0.9000)

1 Like

I can solve it now. Thank you for your support.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.