如何用一组值替换NA


18

我有以下数据框:

library(dplyr)
library(tibble)


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


df

看起来像这样:

# 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

我想做的是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

我该如何实现?

Answers:


8

另外一个选项 :

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

如果你想这样做 dplyr

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


6

这是一种dplyr方法,

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

这使,

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12

4

dplyr

library(dplyr)

df %>%
  mutate_at("score", ~ ifelse(is.na(.), max(., na.rm = TRUE) + cumsum(is.na(.)), .))

结果:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12

3

一个dplyr解决方案。

df %>%
  mutate(na_count = cumsum(is.na(score)),
         score = ifelse(is.na(score), max(score, na.rm = TRUE) + na_count, score)) %>%
  select(-na_count)
## A tibble: 5 x 2
#  source score
#  <chr>  <dbl>
#1 a         10
#2 b          5
#3 c         11
#4 d          3
#5 e         12

2

另一个类似于ThomasIsCoding的解决方案:

> df$score[is.na(df$score)]<-max(df$score, na.rm=T)+(1:sum(is.na(df$score)))
> 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

2

与基础R解决方案相比,它不是很优雅,但仍然可以:

library(data.table)
setDT(df)

max.score = df[, max(score, na.rm = TRUE)]
df[is.na(score), score :=(1:.N) + max.score]

或一行但慢一点:

df[is.na(score), score := (1:.N) + df[, max(score, na.rm = TRUE)]]
df
   source score
1:      a    10
2:      b     5
3:      c    11
4:      d     3
5:      e    12
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.