user1655130
user1655130

Reputation: 429

Shifting row values for multiple columns

I have the following dataframe:

xR <- data.frame("A" = c(15, 13.5, 12, 9.1, NA, NA, NA, NA), 
             "B" = c(NA, 13.6, 8.4, 6.7, 5.6, 2.0, NA, NA), 
             "C" = c(NA, NA, 8.5, 2.43, 1.23, NA, NA, NA))

How do I shift the rows in columns B and C up by 1 row to get:

xR1 <- data.frame("A" = c(15, 13.5, 12, 9.1, NA, NA, NA, NA), 
             "B" = c(13.6, 8.4, 6.7, 5.6, 2.0, NA, NA, NA), 
             "C" = c(NA, 8.5, 2.43, 1.23, NA, NA, NA, NA))

My dataframe has 100+ columns so trying to automate it. Thanks for your help

Upvotes: 1

Views: 466

Answers (4)

GKi
GKi

Reputation: 39667

In base you can use [-1] to skip the first element and c with NA to add NA at the end:

data.frame(xR[1], lapply(xR[-1], function(x) c(x[-1], NA)))
#     A    B    C
#1 15.0 13.6   NA
#2 13.5  8.4 8.50
#3 12.0  6.7 2.43
#4  9.1  5.6 1.23
#5   NA  2.0   NA
#6   NA   NA   NA
#7   NA   NA   NA
#8   NA   NA   NA

or modification in place using the thoughts from @Ricardo:

xR[,-1] <- rbind(xR[-1,-1], NA)
xR
#     A    B    C
#1 15.0 13.6   NA
#2 13.5  8.4 8.50
#3 12.0  6.7 2.43
#4  9.1  5.6 1.23
#5   NA  2.0   NA
#6   NA   NA   NA
#7   NA   NA   NA
#8   NA   NA   NA

or only using sub-setting:

xR[,-1] <- xR[seq_len(nrow(xR)) + 1, -1]

Upvotes: 3

Ricardo Semi&#227;o
Ricardo Semi&#227;o

Reputation: 4456

Using base R:

xR[,2:3] = rbind(xR[-1,2:3], NA)

Then you can change the 2:3 to all the columns that you want.

Upvotes: 1

henhesu
henhesu

Reputation: 851

You can automate this across a wide selection of columns with

xR %>% 
  dplyr::mutate_at(.vars = vars(B:C),
                   .funs = ~ dplyr::lead(.x, 1))

Upvotes: 0

deschen
deschen

Reputation: 10996

library(tidyverse)
xR1 <- xR %>%
  mutate(B = lead(B),
         C = lead(C))

which gives:

     A    B    C
1 15.0 13.6   NA
2 13.5  8.4 8.50
3 12.0  6.7 2.43
4  9.1  5.6 1.23
5   NA  2.0   NA
6   NA   NA   NA
7   NA   NA   NA
8   NA   NA   NA

Automating across many columns (assuming you don't want to do the shifting for column A) is quite easy:

xR1 <- xR %>%
  mutate(across(-A, lead))

Upvotes: 0

Related Questions