R 仅向上一步填充数据框中的列

R 仅向上一步填充数据框中的列,r,R,我想在数据帧中用一个变量填充一个步骤 > id <- rep(1:3,each=2) > trt <- rep(c("A","B"),3) > score <- c("1", "","", 3, "",6) > df <- data.frame(id,trt,score) > df id trt score 1 1 A 1 2 1 B 3 2 A 4 2 B 3 5 3

我想在数据帧中用一个变量填充一个步骤

> id <- rep(1:3,each=2)
> trt <- rep(c("A","B"),3)
> score <- c("1", "","", 3, "",6)

> df <- data.frame(id,trt,score)
> df
  id trt score
1  1   A     1
2  1   B      
3  2   A      
4  2   B     3
5  3   A      
6  3   B     6
> 

I want it to look like this:

    > id <- rep(1:3,each=2)
    > trt <- rep(c("A","B"),3)
    > score <- c(1, "",3, 3, 6,6)
    > df <- data.frame(id,trt,score)
    > df
      id trt score
    1  1   A     1
    2  1   B      
    3  2   A     3
    4  2   B     3
    5  3   A     6
    6  3   B     6

要使用
fill
,当您有空字符串值时,我们需要
NA
。对于非空白值上方的一行,我们可以使用
NA
条件替换空白值,然后使用
fill

library(dplyr)

df %>%
  mutate(score = replace(score, which(score != "") - 1, NA)) %>%
  tidyr::fill(score, .direction = "up")

#  id trt score
#1  1   A     1
#2  1   B      
#3  2   A     3
#4  2   B     3
#5  3   A     6
#6  3   B     6

另一种简单的base R选项是

inds <- which(df$score != '')
inds <- inds[inds > 1]
df$score[inds - 1] <- df$score[inds]
inds
inds <- which(df$score != '')
inds <- inds[inds > 1]
df$score[inds - 1] <- df$score[inds]