如果不满足条件,请在data.frame中引用上面的行

如果不满足条件,请在data.frame中引用上面的行,r,dataframe,reference,R,Dataframe,Reference,使用data.frame颜色: colors <- data.frame(color=c("Red","Light Red","Dark Red","Blue","Turquise", "Dark Blue","Cyan"), level=c("Primary",rep("Secondary",2),"Primary",rep("Secondary",3)), stringsAsFactors = F)

使用data.frame
颜色

colors <- data.frame(color=c("Red","Light Red","Dark Red","Blue","Turquise", "Dark Blue","Cyan"),
                     level=c("Primary",rep("Secondary",2),"Primary",rep("Secondary",3)),
                     stringsAsFactors = F)
所需输出应为:

colorsOutput <- data.frame(color=c("Red","Light Red","Dark Red","Blue","Turquise", "Dark Blue","Cyan"),
                           level=c("Primary",rep("Secondary",2),"Primary",rep("Secondary",3)),
                           primary.color=c("Red","Red","Red","Blue","Blue", "Blue", "Blue"),
                           stringsAsFactors = F)

colorsOutput考虑到您的
数据。帧
已排序(先是原色,然后是次色),您可以执行以下操作:

colors$primary.color <- colors$color[colors$level=="Primary"][cumsum(colors$level=="Primary")]
colors
#      color     level primary.color
#1       Red   Primary           Red
#2 Light Red Secondary           Red
#3  Dark Red Secondary           Red
#4      Blue   Primary          Blue
#5  Turquise Secondary          Blue
#6 Dark Blue Secondary          Blue
#7      Cyan Secondary          Blue

colors$primary.color这是“最后一次观察结转”的一个很好的用例,即
zoo
软件包中的
na.locf
功能

首先获取原色所在位置的索引:

idx <- colors$level == "Primary"
idx
idx <- colors$level == "Primary"
colors[idx, "primary"] <- colors$color[idx]
colors$primary <- zoo::na.locf(colors$primary)