Reputation: 513
this is my dataframe:
df<-as.data.frame(matrix(seq(1:20),5,5))
What I need to adjust is the column. Basically I need to exclude the first row and then move up all the columns letting the last row with repeated values.
Its sound confusing, probably but the result should be this:
V1 V2 V3 V4 V5
1 2 7 12 17 2
2 3 8 13 18 3
3 4 9 14 19 4
4 5 10 15 20 5
5 5 10 15 20 5
Actually, I know how to do it but it is not an elegant way.
Any help?
Upvotes: 2
Views: 60
Reputation: 887221
An option is rbind
the dataset by removing the first row, with the last row of the dataset
rbind(df[-1, ], df[nrow(df),])
Or using index
df[c(2:nrow(df), nrow(df)),]
Upvotes: 3
Reputation: 1630
Here is an example. Though I would like to know what you mean by elegant? Do you mean get a readable code? less lines of code? better performance?
library(tidyverse)
df<-as.data.frame(matrix(seq(1:20),5,5))
df <- df %>% slice(-1)
df[dim(df)[1] +1,] <- df[dim(df)[1],]
Upvotes: 2