Как заменить NA с набором значений - PullRequest
18 голосов
/ 14 февраля 2020

У меня есть следующий фрейм данных:

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

Как этого достичь?

Ответы [ 7 ]

8 голосов
/ 14 февраля 2020

Другой вариант:

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 голосов
/ 14 февраля 2020

Вот подход 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
6 голосов
/ 14 февраля 2020

Базовый раствор R

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

такой, что

> 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
4 голосов
/ 14 февраля 2020

С 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 голосов
/ 14 февраля 2020

A 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 голосов
/ 14 февраля 2020

Не совсем элегантно по сравнению с решениями base 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
2 голосов
/ 14 февраля 2020

Еще один, очень похожий на решение 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
...