0

Suppose we have a data frame like this:

Value  Image
24.34  pic_00001
232.4  pic_00002
342.34 pic_00003

The Image column continues in the same sequence up to pic_10000 in the full data set.

I'd like to replace the Image column values so that it starts at pic_00002 - essentially deleting pic_00001 and shifting them all up. The Values column should stay the same. In other words, the output should look like:

Value  Image
24.34  pic_00002
232.4  pic_00003
342.34 pic_00004

Up to pic_10001 (which will need to be generated if the method is to shift all column values up by 1)

Does anybody know how to do this?

  • 1
    Does the following work for you: `df$Shifted <- c(df$Image[-1], NA)` – tpetzoldt Jun 30 '21 at 15:36
  • 1
    If you need it to start at 2, then change (from your [previous question's accepted answer](https://stackoverflow.com/a/68196537/3358272)) `sprintf("pic_%05d", seq_len(NROW(dat)))` with `sprintf("pic_%05d", seq_len(NROW(dat))+1L)` – r2evans Jun 30 '21 at 15:37
  • Tidyverse's `lead()` seems useful too. – Limey Jun 30 '21 at 15:40
  • Does this answer your question: ["shift values in single column of dataframe up"](https://stackoverflow.com/questions/25995257/shift-values-in-single-column-of-dataframe-up)? To be clear, [this](https://stackoverflow.com/a/25691035) is likely the cleanest answer: `library(dplyr)` followed by your_`df %>% mutate(Image = lead(Image, n = 1, default = NA))`; I explicitly specified `n = 1` to illustrate a shift by 1, and `default = NA` to show the value used to fill the "stub" at the bottom of the column. – Greg Jun 30 '21 at 15:43
  • @Limey I actually meant to make it `lead()` rather than `lag()`, but I couldn't edit it in time, so I had to delete and retype. :/ – Greg Jun 30 '21 at 15:45

1 Answers1

1

I'd use lead() from dplyr.

library(dplyr)

x <- tribble(
  ~value,   ~image,
  1,        "zero",
  2,        "one",
  3,        "two",
)

x %>% 
  mutate(lead_image = lead(image, 1, default = "manual three"))
#> # A tibble: 3 x 3
#>   value image lead_image  
#>   <dbl> <chr> <chr>       
#> 1     1 zero  one         
#> 2     2 one   two         
#> 3     3 two   manual three

Created on 2021-06-30 by the reprex package (v2.0.0)

Oliver
  • 1,098
  • 1
  • 11
  • 16