I have a large data.frame and I want to create a new data.frame with randomly selected rows based on two columns.
There are 90 unique elkIDs with ~48 rows per FixDate. I would like to make a new data.frame with 90 unique elkIDs with 4 randomly selected rows per each FixDate.
Data looks like this:
> head(df)
elkID X Y Fix.Date.Time FixDate
1 245 550345.1 4826676 2010-02-24 10:00:58 2010-02-24
2 245 550217.9 4826519 2010-02-24 10:30:47 2010-02-24
3 245 550066.3 4826478 2010-02-24 11:00:41 2010-02-24
4 245 549912.6 4826419 2010-02-24 11:30:48 2010-02-24
5 245 549977.3 4826438 2010-02-24 12:00:55 2010-02-24
6 245 549795.1 4826294 2010-02-24 12:30:29 2010-02-24
I want it to look like this (4 rows per FixDate for each unique elkID):
> df2
elkID X Y Fix.Date.Time FixDate
1 245 550345.1 4826676 2010-02-24 10:00:58 2010-02-24
2 245 550217.9 4826519 2010-02-24 10:30:47 2010-02-24
3 245 550066.3 4826478 2010-02-24 11:00:41 2010-02-24
4 245 549912.6 4826419 2010-02-24 11:30:48 2010-02-24
5 245 549977.3 4826438 2010-02-24 12:00:55 2010-02-25
6 245 549795.1 4826294 2010-02-24 12:30:29 2010-02-25
Using RStudio V0.99.467 & R3.2.1
If you want to loop through them you can try the following:
# initialize a new dataframe to store new data
newdf = NULL
# extract unique elk IDs
IDs = unique(df$elkID)
# create a loop to subset each ID first (i loop) and secondly
# loop through the unique dates (j loop)
for(i in 1:length(IDs)){
data1 = df[df$elkID == IDs[i],]
dates = unique(data1$FixDate)
for(j in 1:length(dates)){
data2 = data1[data1$FixDate == dates[j],]
# this should select 4 rows at random for each particular ID and date
data2 = data2[sample(1:nrow(data2),4),]
newdf = rbind(newdf,data2)
}
}
head(newdf)
tail(newdf)
Does this do what you are looking for?
For large dataframes I recommend the package data.table
:
library(data.table)
setDT(df)
df[, .SD[sample(.N, 4)] , by=.(elkID, FixDate)] #or
df[, .SD[sample(.N, 4)] , keyby=.(elkID, FixDate)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.