How to shuffle a dataframe in R by rows
Last Updated :
14 Sep, 2021
In this article, we will discuss how to shuffle a dataframe by rows in the R programming language.
Shuffling means reordering or rearranging the data. We can shuffle the rows in the dataframe by using sample() function. By providing indexing to the dataframe the required task can be easily achieved.
Syntax:
dataframe[sample(1:nrow(dataframe)), ]
Where.
- dataframe is the input dataframe
- sample() function is used to shuffle the rows that takes a parameter with a function called nrow() with a slice operator to get all rows shuffled.
- nrow() is sued to get all rows by taking the input parameter as a dataframe
Example: R program to create a dataframe with 3 columns and 6 rows and shuffle the dataframe by rows
R
data= data.frame (id= c (1,2,3,4,5,6),
name= c ( "sravan" , "bobby" , "ojaswi" , "gnanesh" ,
"rohith" , "satwik" ),
marks= c (89,90,98,78,98,78))
print (data)
print ( "_______________________________________________________" )
shuffled_data= data[ sample (1: nrow (data)), ]
print (shuffled_data)
|
Output:
Example: R program to create a student dataframe with 2 columns and 3 rows
R
data = data.frame (id= c (1, 2, 3), name= c (
"sravan" , "bobby" , "ojaswi" ))
print (data)
print ( "_______________________________________________________" )
shuffled_data = data[ sample (1: nrow (data)), ]
print (shuffled_data)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...