在r中应用索引

时间:2018-10-15 15:33:32

标签: r indexing

我已为数据建立索引。我希望将索引中的第一个值应用于该索引中的所有其他值。以下是我制作的示例。

index<-c(1,1,1,2,2,2,2,2,3,3)
animal<-c("cat","dog","lion","chicken","frog","goat","sheep","elephant","tiger", "bear")
df<-as.data.frame(cbind(index,animal))

index   animal
1      1      cat
2      1      dog
3      1     lion
4      2  chicken
5      2     frog
6      2     goat
7      2    sheep
8      2 elephant
9      3    tiger
10     3     bear

结果应如下所示:

index   animal
1      1      cat
2      1      cat
3      1      cat
4      2  chicken
5      2  chicken
6      2  chicken
7      2  chicken
8      2  chicken
9      3    tiger
10     3    tiger

1 个答案:

答案 0 :(得分:0)

这是一个选择

df$animal <- with(df, animal[cummax(seq_along(index) * !duplicated(index))])