vendredi 13 avril 2018

How to switch random number of rows' column values in a dataset?

Learning R code here. Here's my dataset then I'll explain in detail what I am attempting to accomplish:

alp <- c("a", "b", "c","d", "e", "f")
num <- c(1:6)
my.set <- data.frame(num, alp)

It looks like this:

num alp  
1   a  
2   b  
3   c  
4   d  
5   e  
6   f  

A dataset with 6 rows and 2 columns. (Sorry, I spent a lot of time writing this all out and I can't figure out how to include spaces for the dataset to appear nice on screen)

I need to create either a for-loop or a function where I can randomly select a number of rows (between 0 and 6 rows) and switch their respective column values. In other words, select a random number of rows where we strip the labels, and flip the num value with the alp value.

To get it to look something like this (given that 2 rows were selected to be changed):

num alp  
a  1  
2  b  
3  c  
d  4  
5  e  
6  f  

I am doing it this way: For each row, I want to flip a coin. And if it's heads (or 0), then its column values are switched. If it's tails (or 1), nothing happens to it.

Now I have this so far, but it's throwing error messages:

for (j in 1:nrow(my.set)) {
  flip <- sample(0:1, 1, replace = TRUE)
  if (flip==0) {
      my.set[j,1:2] <- my.set[j,2:1]
  } else {
      my.set[j,1:2] <- my.set[j,1:2]
  }
}

So what am I doing wrong and how can I fix this? Any help is appreciated!

Thank you!




Aucun commentaire:

Enregistrer un commentaire