Here are some sample data:

```df <- data.frame(matrix(rnorm(80), nrow=40))
df\$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)

df[sample(nrow(df), 3), ] #samples 3 random rows from df, without replacement.```

To e.g. just sample 3 random rows from 'pink' color - using library(kimisc):

```library(kimisc)
sample.rows(subset(df, color == "pink"), 3)```

or writing custom function:

```sample.df <- function(df, n) df[sample(nrow(df), n), , drop = FALSE]
sample.df(subset(df, color == "pink"), 3)```

I want to sample 3 (or n) random rows from each level of the factor. I.e. the new df would have 12 rows (3 from blue, 3 from red, 3 from yellow, 3 from pink).

I am looking for a really simple solution. Jul 2, 2018 3,083 views

## 1 answer to this question.

You can assign a random ID to each element that has a particular factor level using ave. Then you can select all random IDs in a certain range.

```rndid <- with(df, ave(X1, color, FUN=function(x) {sample.int(length(x))}))
df[rndid<=3,]``` answered Jul 2, 2018 by
• 6,380 points

## How to iterate over rows in a Dataframe in pandas (Python)?

You can use IMHO: for ind in df.index: ...READ MORE

+1 vote

## How can I find number of rows in a dataframe, and how to find the number of rows that dont have null values

Use nrow() to find number of rows ...READ MORE

## How to select rows in a range from dataframe?

This should do it integer_location = np.where(df.index == ...READ MORE

+1 vote

## How to convert a list of vectors with various length into a Data.Frame?

We can easily use this command as.data.frame(lapply(d1, "length< ...READ MORE

## In data frame how to spilt strings into values?

You can do this using dplyr and ...READ MORE

## How to convert a text mining termDocumentMatrix into excel or csv in R?

By assuming that all the values are ...READ MORE