如何在R中滞后数据帧的特定列

时间:2019-12-05 09:18:23

标签: r

输入 (说d是下面的数据框。)

a  b  c
1  5  7
2  6  8
3  7  9

我想将b列的内容向下移动一个位置,并在b的第一个位置放置一个任意数字。我该怎么做呢?在这方面的任何帮助,我将不胜感激。谢谢。

我尝试了c(6,tail(d [“ b”],-1)),但它不会产生(6,5,6)。

输出

a  b  c
1  6  7
2  5  8
3  6  9

4 个答案:

答案 0 :(得分:1)

改为使用head

df$b <- c(6, head(df$b, -1))
#  a b c
#1 1 6 7
#2 2 5 8
#3 3 6 9

您还可以在lag中使用dplyr

library(dplyr)
df %>% mutate(b = lag(b, default = 6))

或在shift中的data.table

library(data.table)
setDT(df)[, b:= shift(b, fill = 6)]

答案 1 :(得分:1)

如果愿意,dplyr解决方案可以将lag与显式default参数一起使用:

library(dplyr)

d <- tibble(a = 1:3, b = 5:7, c = 7:9)

d %>% mutate(b = lag(b, default = 6))
#> # A tibble: 3 x 3
#>       a     b     c
#>   <int> <dbl> <int>
#> 1     1     6     7
#> 2     2     5     8
#> 3     3     6     9

reprex package(v0.3.0)

创建于2019-12-05

答案 2 :(得分:0)

这是一种类似于@Ronak Shahhead方法的解决方案

df <- within(df,b <- c(runif(1),b[-1]))

将均匀随机变量添加到b列的第一位:

> df
  a         b c
1 1 0.6644704 7
2 2 6.0000000 8
3 3 7.0000000 9

答案 3 :(得分:-1)

下面的最佳解决方案将有助于解决任何滞后或领先情况

d <- data.frame(a=c(1,2,3),b=c(5,6,7),c=c(7,8,9))

d1 <- d %>% arrange(b) %>% group_by(b) %>% 
mutate(b1= dplyr::lag(b, n = 1, default = NA))