Home > other >  How to take values in every other row (odd) and shift them to be in every row (even and odd) or swit
How to take values in every other row (odd) and shift them to be in every row (even and odd) or swit

Time:11-04

The question is fairly explicit. 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"

CodePudding user response:

If I understand correctly, create an index that selects the values you'd like

> idx = seq(2, nrow(output), by = 2)

and use idx - 1 to select the rows to be replaced

> output[idx - 1, "work"] = output[idx, "work"]
> head(output)
  work
1    B
2    B
3    C
4    C
5    A
6    A

It's not really clear what you'd like to happen to the last row, if there are an odd number of rows?

Note that a much more efficient / R way to generate the original data is perhaps

df = data.frame(work = character(500))
idx = seq(2, nrow(df), by = 2)
df[idx, "work"] = sample(c("A", "B", "C"), length(idx), replace = TRUE)

CodePudding user response:

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