Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

Randomly sampling rows from particular months in a data set

$
0
0

I was given this task in R:

"Randomly select 10 trading days from each of the following months: January 2019 to June 2019 (6 months total)".

I have a CSV file of a company's stock trading history from the last 5 years (dates, opening price, closing price, changes, etc.) that I imported into R using this code (reading the file; setting date format; extracting all 6 relevant months):

SHAPIRENG5YEARS <- read.csv(file="C:\\Users\\Ron\\OneDrive\\5year.csv", header=TRUE, sep=",") #Choosing Shapir Engineering stock (last 5 years)
SHAPIRENG5YEARS$Date = as.Date(as.character(SHAPIRENG5YEARS$Date), format = "%d/%m/%Y")
January19=SHAPIRENG5YEARS[(SHAPIRENG5YEARS$Date > "2019-01-01"& SHAPIRENG5YEARS$Date < " 2019-01-31" ) ,]
February19=SHAPIRENG5YEARS[(SHAPIRENG5YEARS$Date > "2019-02-03"& SHAPIRENG5YEARS$Date < " 2019-02-28" ) ,]
March19=SHAPIRENG5YEARS[(SHAPIRENG5YEARS$Date > "2019-03-09"& SHAPIRENG5YEARS$Date < " 2019-03-31" ) ,]
April19=SHAPIRENG5YEARS[(SHAPIRENG5YEARS$Date > "2019-04-01"& SHAPIRENG5YEARS$Date < " 2019-04-30" ) ,]
May19=SHAPIRENG5YEARS[(SHAPIRENG5YEARS$Date > "2019-05-01"& SHAPIRENG5YEARS$Date < " 2019-05-30" ) ,]
June19=SHAPIRENG5YEARS[(SHAPIRENG5YEARS$Date > "2019-06-02"& SHAPIRENG5YEARS$Date < " 2019-06-30" ) ,]

Now I don't know what should I do. I can sample one month using

January19sample <-January19[sample(nrow(January19), 10), ]

but I want to avoid doing this six times (once for each month). Ideally I'd like to sample all 10*6=60 values from the original big data frame.

Edit: I'm still struggling. I tried this (It is not good because I'm getting a list of 6 lists, each with length of 18 and not random 10 picks):

SamplesOfMonths=list(c(January19),c(February19),c(March19),c(April19),c(May19),c(June19))
TopSamples=c(1:10)
LowSamples=c(1:10)
for (i in 1:6)
{
    Changer=unlist(SamplesOfMonths[i])
    TopSamples[i]=sample(Changer, 10)[2]
    LowSamples[i]=sample(Changer, 10)[1]
    print(sample(Changer, 10))
}

Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>