i am currently trying to move my 28th row in a dataframe of 30 rows to the 13th row of my dataframe. I have tried the following code, after having seen this post, but I do not fully understand it so it doesn't work. Could anyone help ?
Here is the post I have seen :
Change row order in a matrix/dataframe
library(data.table)
setDT(join_21_20)[join_21_20[,.I[1:(.N 1)] ,by=
(seq_len(nrow(join_21_20))-15)%/' 1]$2019]
Here is a structure of my dataset for reproducibility :
structure(list(compte = c("Operating income", "Results from assets sale",
"Total Operating income and Results from assets sale", "Supplies",
"Staff costs", "Other expenses"), `2021` = c("827208", "75226",
"902434", "-91590", "-307364", "-372603"), `2020` = c("528398",
"0", "528398", "-58871", "-282106", "-338288"), `2019` = c(1789537,
11211, 1800748, -199035, -523918, -579301)), row.names = c(NA,
6L), class = "data.frame")
CodePudding user response:
You can use indexing as described in the answer to this question.
df <- structure(list(compte = c("Operating income", "Results from assets sale",
"Total Operating income and Results from assets sale", "Supplies",
"Staff costs", "Other expenses"), `2021` = c("827208", "75226",
"902434", "-91590", "-307364", "-372603"), `2020` = c("528398",
"0", "528398", "-58871", "-282106", "-338288"), `2019` = c(1789537,
11211, 1800748, -199035, -523918, -579301)), row.names = c(NA,
6L), class = "data.frame")
df <- df[c(1:2,4,3,5:nrow(df)),]
df
This prints the dataframe in order 1,2,4,3,5,6.
For your particular case the answer looks as follows:
df <- df[c(1:12,28,13:27,29:nrow(df)),]
In detail, you index the dataframe by selecting df[ROWS, COLUMNS], you provide a vector of the rows that you want, and leaving the column selector empty means you select all the columns as-is. The row vector is a collection of index ranges or singular indexes in the order that you want (one-indexed).