Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
6 views
in R Programming by (2.6k points)
Can someone tell me a function which can return a specified no. of rows picked randomly without any replacement from a DataFrame in R?

1 Answer

+1 vote
by
edited

To sample random rows from a data frame, use the sample() function as follows:

To create a data frame:

a<- c(100,120,3,67)

b <- c(4,5,NA,90)

c <- c(NA,3,6,7)

d <- c("A","B","C","D")

data <- data.frame(col1 = a

                  ,Col2 = b,

                  Col3 =c,

                  Col4 = d)

head(data)

Output:

  col1 Col2 Col3  Col4

1  100    4    NA   A

2  120    5    3    B

3    3   NA    6    C

4   67   90    7    D

To select random rows from the above data frame:

data[sample(nrow(data), 3), ]

Output:

  col1 Col2 Col3 Col4

3    3  NA    6     C

1  100   4   NA    A

4   67  90   7    D

If you want to explore more in R programming then watch this R programming tutorial for beginner:

Related questions

+1 vote
1 answer
0 votes
1 answer
+4 votes
2 answers
asked May 29, 2019 in R Programming by Krishna (2.6k points)

Browse Categories

...