2

これは私のデータフレームです:

library(zoo)
library(dplyr)

df <- data.frame(
  id = rep(1:4, each = 4), 
  status = c(
    NA, "a", "c", "a", 
    NA, "c", "c", "c",
    NA, NA, "a", "c",
    NA, NA, "c", "c"),
  otherVar = letters[1:16],
  stringsAsFactors = FALSE)

変数 status については、次の観測をグループ (id) 内で逆方向に実行したいと考えています。

df %>% group_by(id) %>% na.locf(fromLast = TRUE) %>% ungroup

ただし、「c」のみを逆方向に実行し、「a」は実行しないようにします。

変数ステータスから:

NA "a" "c" "a" NA "c" "c" "c" NA NA "a" "c" NA NA "c" "c"

私は手に入れたい:

NA "a" "c" "a" "c" "c" "c" "c" NA NA "a" "c" "c" "c" "c" "c"

それぞれ:

data.frame(
  id = rep(1:4, each = 4), 
  status = c(
    NA, "a", "c", "a", 
    "c", "c", "c", "c",
    NA, NA, "a", "c",
    "c", "c", "c", "c"),
  otherVar = letters[1:16],
  stringsAsFactors = FALSE)

これを行う方法はありますか?

4

2 に答える 2

1

tidyr:fillの作成に基づくソリューション。を使用して。次の値が であることを確認した後、これを使用して実際の列に値を入力します。dummyStatusfilldummyStatus.direction = "up"dummyStatusNAstatusc

library(dplyr)
library(tidyr)
df %>% group_by(id) %>%
    mutate(dummyStatus = status) %>%
    fill(dummyStatus, .direction = "up" ) %>%
    mutate(status = ifelse(is.na(status) & lead(dummyStatus)=="c","c",status)) %>%
    select(-dummyStatus) %>% as.data.frame()

  #    id status otherVar
  # 1   1   <NA>        a
  # 2   1      a        b
  # 3   1      c        c
  # 4   1      a        d
  # 5   2      c        e
  # 6   2      c        f
  # 7   2      c        g
  # 8   2      c        h
  # 9   3   <NA>        i
  # 10  3   <NA>        j
  # 11  3      a        k
  # 12  3      c        l
  # 13  4      c        m
  # 14  4      c        n
  # 15  4      c        o
  # 16  4      c        p

データ:

df <- data.frame(
  id = rep(1:4, each = 4), 
  status = c(
    NA, "a", "c", "a", 
    NA, "c", "c", "c",
    NA, NA, "a", "c",
    NA, NA, "c", "c"),
  otherVar = letters[1:16],
  stringsAsFactors = FALSE)
于 2018-05-07T16:22:57.430 に答える