Home > OS >  Applying a function to switch the position of rows repeatedly
Applying a function to switch the position of rows repeatedly

Time:10-19

I am currently working on a super long dataframe in R that looks like this

Year Value
1912 0.5
1912 0.6
1913 0.2
1913 0.3
1914 1.4
1915 1.2

And I need to switch the position every two rows so that it looks like this

Year Value
1912 0.6
1912 0.5
1913 0.3
1913 0.2
1914 1.2
1915 1.4

I feel so confused about if there is anything I can do to achieve that or I need to write the function by myself

CodePudding user response:

We can group by Year and reverse the 'Value' column

library(dplyr)
df1 %>%
    group_by(Year) %>%
    mutate(Value = rev(Value)) %>%
    ungroup

data

df1 <- structure(list(Year = c(1912L, 1912L, 1913L, 1913L, 1914L, 1915L
), Value = c(0.5, 0.6, 0.2, 0.3, 1.4, 1.2)), 
class = "data.frame", row.names = c(NA, 
-6L))
  •  Tags:  
  • r
  • Related