3

I would like to create a new column based on an existing column, but a row above

Starting with:

df <- data.frame(a=c(1:10), b=c("red", "yellow", "blue", "green", "yellow", "purple", "blue", "green", "yellow", "purple"))

With the result looking like:

df <- data.frame(a=c(1:10), b=c("red", "yellow", "blue", "green", "yellow", "purple", "blue", "green", "yellow", "purple"), c=c("na", "red", "yellow", "blue", "green", "yellow", "purple", "blue", "green", "yellow"))

Thank you for any help you are able to provide

Pete
  • 600
  • 1
  • 6
  • 16

2 Answers2

1

One way with shift from package data.table:

library(data.table)
df$c <- shift(df$b, 1)

df
#    a      b      c
#1   1    red   <NA>
#2   2 yellow    red
#3   3   blue yellow
#4   4  green   blue
#5   5 yellow  green
#6   6 purple yellow
#7   7   blue purple
#8   8  green   blue
#9   9 yellow  green
#10 10 purple yellow
LyzandeR
  • 37,047
  • 12
  • 77
  • 87
1

Using dplyr this can be done with mutate and lag functions:

library(dplyr)
mutate(df, c = lag(b))

#>     a      b      c
#> 1   1    red   <NA>
#> 2   2 yellow    red
#> 3   3   blue yellow
#> 4   4  green   blue
#> 5   5 yellow  green
#> 6   6 purple yellow
#> 7   7   blue purple
#> 8   8  green   blue
#> 9   9 yellow  green
#> 10 10 purple yellow
markdly
  • 4,394
  • 2
  • 19
  • 27