如何用一组值替换 NA

sca*_*der 17 replace if-statement r dplyr tibble

我有以下数据框:

library(dplyr)
library(tibble)


df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) ) 


df
Run Code Online (Sandbox Code Playgroud)

它看起来像这样:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA
Run Code Online (Sandbox Code Playgroud)

我想要做的是NA用现有的值范围替换分数列max + n。其中n范围从 1 到总行数df

导致这个(手工编码):

  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Ron*_*hah 10

另外一个选项 :

transform(df, score = pmin(max(score, na.rm = TRUE) + 
                      cumsum(is.na(score)), score, na.rm = TRUE))

#  source score
#1      a    10
#2      b     5
#3      c    11
#4      d     3
#5      e    12
Run Code Online (Sandbox Code Playgroud)

如果你想在 dplyr

library(dplyr)
df %>% mutate(score = pmin(max(score, na.rm = TRUE) + 
                      cumsum(is.na(score)), score, na.rm = TRUE))
Run Code Online (Sandbox Code Playgroud)


Tho*_*ing 6

一个基本的 R 解决方案

df$score[is.na(df$score)] <- seq(which(is.na(df$score))) + max(df$score,na.rm = TRUE)
Run Code Online (Sandbox Code Playgroud)

以至于

> df
# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12
Run Code Online (Sandbox Code Playgroud)


Sot*_*tos 6

这是一个dplyr方法,

df %>% 
 mutate(score = replace(score, 
                       is.na(score), 
                       (max(score, na.rm = TRUE) + (cumsum(is.na(score))))[is.na(score)])
                       )
Run Code Online (Sandbox Code Playgroud)

这使,

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12
Run Code Online (Sandbox Code Playgroud)