Reputation: 131
Hi How can I subset 2 different N random samples in a data frame. See example below.
I have df the main dataset. I need 2 subsets of the main dataset. I got 2 subsets by getting 3 random rows from the main dataset. However I need those 2 subsets to be unique with each other.
> df = data.frame(matrix(rnorm(20), nrow=10))
> df
X1 X2
1 0.19234071 -0.86702704
2 -0.18264853 1.75276062
3 0.75824257 -0.51314220
4 -0.84571563 -1.24841675
5 0.75470152 1.51408945
6 1.04546517 1.33292716
7 -0.51449011 -1.51275633
8 1.36014747 0.07400024
9 -0.02397481 0.17177997
10 -1.37967248 -0.50416489
df1 = df[sample(nrow(df), 3), ]
df1
X1 X2
10 -1.3796725 -0.5041649
1 0.1923407 -0.8670270
4 -0.8457156 -1.2484167
df2 = df[sample(nrow(df), 3), ]
df2
X1 X2
3 0.7582426 -0.5131422
4 -0.8457156 -1.2484167
6 1.0454652 1.3329272
As you can see the random subsets df1 and df2 have same row which is the row 4. I need 2 random subsets of the dataframe that had different rows.
Upvotes: 1
Views: 189
Reputation: 2764
You could also do something like this-
idx <- sample(seq(1, 2), size = nrow(df), replace = TRUE, prob = c(.8, .2))
set1 <- df[idx == 1,]
set2 <- df[idx == 2,]
Output-
> set1
X1 X2
1 -0.85768451 -0.1545485
2 -0.76420259 1.2054883
3 -0.91973457 1.4867429
6 -1.07558176 0.2527374
7 0.03189408 1.4057502
8 0.64270649 1.3742131
9 1.59246097 -0.3845688
10 -0.14158552 -1.5792062
> set2
X1 X2
4 -0.6317524 0.06571271
5 0.5005460 0.46277511
Note**- You can change split percent in sample
function. I have used 80-20%
.
Upvotes: 0
Reputation: 887981
We can create a function if we nee to reuse the same logic
f1 <- function(data, n) {
data[sample(nrow(data), n),]
}
Or if we need to create train/test dataset, we can use split
lst1 <- split(df, seq_len(nrow(df)) %in% sample(nrow(df), 3))
Upvotes: 0
Reputation: 3183
If you want to split the data into 2 distinct sets, you can create an index
and split the frames, something like this
set.seed(42)
idx <- sample(1:nrow(df), 3)
df1 <- df[idx, ]
df2 <- df[-idx, ]
df1
X1 X2
10 1.359814 0.6919378
9 1.248144 0.9783253
3 1.903994 0.4371896
df2
X1 X2
1 -0.3743900 0.54040310
2 -0.3204993 0.02383999
4 -0.2552918 0.94148533
5 -0.7327228 -1.25263998
6 -1.0648850 0.06567222
7 -0.2147909 -0.19137447
8 1.2148835 1.36361765
For much more complex splits, do see caret::createDataPartition
Upvotes: 2