如何创建R代码以根据条件检查下一个观察

时间:2017-03-15 13:51:27

标签: r dataframe sequence

这是一个示例数据集

obs <- 1:10
x1 <- c("a", "b", "a", "d", "f", "a", "c", "a", "c", "d")
dset<-data.frame(obs,x1)
> dset
   obs x1
1   1  a
2   2  b
3   3  a
4   4  d
5   5  f
6   6  a
7   7  c
8   8  a
9   9  c
10 10  d

n是观察的顺序,我想创建一个变量(x2),这样每当x1为“a”时,x2就会记录下面的观察结果

所以像这样的数据集:

   obs x1 x2
1   1  a  b
2   2  b  NA
3   3  a  d
4   4  d  NA
5   5  f  NA
6   6  a  c
7   7  c  NA
8   8  a  c
9   9  c  NA
10 10  d  NA

提前致谢!

2 个答案:

答案 0 :(得分:3)

您也可以尝试:

dset$x2 <- NA
x1 <- as.character(dset$x1) # in case its factor and not string
inds <- which(x1=="a")
dset$x2[inds] <- x1[inds+1]

  # obs x1   x2
# 1    1  a    b
# 2    2  b <NA>
# 3    3  a    d
# 4    4  d <NA>
# 5    5  f <NA>
# 6    6  a    c
# 7    7  c <NA>
# 8    8  a    c
# 9    9  c <NA>
# 10  10  d <NA>

答案 1 :(得分:2)

这将做你想要的:

obs <- 1:10
x1 <- c("a", "b", "a", "d", "f", "a", "c", "a", "c", "d")
dset<-data.frame(obs,x1, stringsAsFactors = FALSE)
dset$x2 <- ifelse(dset$x1=="a", c(dset$x1[-1], NA), NA)

结果:

> dset
#   obs x1   x2
#1    1  a    b
#2    2  b <NA>
#3    3  a    d
#4    4  d <NA>
#5    5  f <NA>
#6    6  a    c
#7    7  c <NA>
#8    8  a    c
#9    9  c <NA>
#10  10  d <NA>

或(没有stringsAsFactors=FALSE

dset <- data.frame(obs=1:10, x1=c("a", "b", "a", "d", "f", "a", "c", "a", "c", "d"))
dset$x2 <- ifelse(dset$x1=="a", c(as.character(dset$x1[-1]), NA), NA)
dset