2017-10-20 32 views
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")) 

感謝您的幫助,您能提供

回答

1

一種方式與shift從包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 
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