June 2007
Beginner to intermediate
950 pages
27h 8m
English
In bootstrapping or cross-validation we might want to select certain rows from the dataframe at random. We use the sample function to do this: the default replace = FALSE performs shuffling (each row is selected once and only once), while the option replace = TRUE (sampling with replacement) allows for multiple copies of certain rows. Here we use replace = F to select a unique 8 of the 20 rows at random:
worms[sample(1:20,8),]
Field.Name Area Slope Vegetation Soil.pH Damp Worm.density
7 Church.Field 3.5 3 Grassland 4.2 FALSE 3
17 Cheapside 2.2 8 Scrub 4.7 TRUE 4
19 Gravel.Pit 2.9 1 Grassland 3.5 FALSE 1
14 Observatory.Ridge 1.8 6 Grassland 3.8 FALSE 0
12 North.Gravel 3.3 1 Grassland 4.1 FALSE 1
9 The.Orchard 1.9 0 Orchard 5.7 FALSE 9
11 Garden.Wood 2.9 10 Scrub 5.2 FALSE 8
8 Ashurst 2.1 0 Arable 4.8 FALSE 4
Note that the row numbers are in random sequence (not sorted), so that if you want a sorted random sample you will need to order the dataframe after the randomization.
Read now
Unlock full access