Search code examples
rdata-cleaning

How to take values in every other row (odd) and shift them to be in every row (even and odd) or switch them to other rows (even)?


How do you take values in every other row (odd) and shift them to every row (even and odd) or switch them to other rows (even)? In a dataframe, I have values in every other row. I would like them to be in every row of the column. How do I achieve this? An alternative solution would be to switch them so that they are only in even, but not odd.

Example of what it currently looks like:

set.seed(5)
output<-data.frame(matrix("", nrow=500, ncol=1))
for(i in 1:nrow(output)){
  if(i %% 2 == 0){
    output[i,1] <- sample(c("A","B","C"),1,replace = T)
  }
}
colnames(output) <- "work"

I would like it to appear as:

set.seed(5)
output<-data.frame(matrix("", nrow=500, ncol=1))
for(i in 1:nrow(output)){
    output[i,1] <- sample(c("A","B","C"),1,replace = T)
}
colnames(output) <- "work"

Solution

  •   row_odd <- seq_len(nrow(output)) %% 2 
      output[row_odd == 1, 1] <- data_row_even
      output[row_odd == 0, 1] <- NA