根据上一行创建一个基于现有列的新列

3

我想基于现有列创建一个新列,但是在上一行

起始于:

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

结果看起来像这样:
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"))

感谢您能提供的任何帮助。
2个回答

1
使用dplyr,可以通过mutatelag函数来实现此操作:
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

1

使用 data.table 包中的 shift 函数的一种方式:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接