0

How to use this command in R for a range of numbers?

PR01 <- Pra_Ruz[grep("-01-", Pra_Ruz$Date), ]

I mean

PR01 <- Pra_Ruz[grep("-01-", Pra_Ruz$Date), ]
PR02 <- Pra_Ruz[grep("-02-", Pra_Ruz$Date), ]
PR03 <- Pra_Ruz[grep("-03-", Pra_Ruz$Date), ]
PR04 <- Pra_Ruz[grep("-04-", Pra_Ruz$Date), ]
....
zx8754
  • 52,746
  • 12
  • 114
  • 209
Anna-Kat
  • 193
  • 7

1 Answers1

1

It is easier to help if you provide data in a reproducible format with expected output.

Consider this as your data -

Pra_Ruz <- data.frame(Date = as.Date(c('2012-01-31', '2020-12-28', 
        '2015-10-11', '2014-04-16', '2016-03-22')), a = 1:5)

Pra_Ruz
#        Date a
#1 2012-01-31 1
#2 2020-12-28 2
#3 2015-10-11 3
#4 2014-04-16 4
#5 2016-03-22 5

You can specify the range in regex using [1-4]

Pra_Ruz[grep("-0[1-4]-", Pra_Ruz$Date), ]

#        Date a
#1 2012-01-31 1
#4 2014-04-16 4
#5 2016-03-22 5

Another option -

If these are date objects you can extract the month value from it and then subset.

Pra_Ruz[as.integer(format(Pra_Ruz$Date, '%m')) %in% 1:4, ]

If you want to split the datasets in multiple individual dataframes

data <- split(Pra_Ruz, format(Pra_Ruz$Date, '%m'))
names(data) <- paste0('PR', names(data))
list2env(data, .GlobalEnv) #Not recommended, do only if necessary. 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213