簡體   English   中英

R 中另一列值為 NA 時重新編碼 NA

[英]Recode NA when another column value is NA in R

我有一個快速重新編碼的問題。 這是我的示例數據集:

df <- data.frame(id = c(1,2,3),
                 i1 = c(1,NA,0),
                 i2 = c(1,1,1))

> df
  id i1 i2
1  1  1  1
2  2 NA  1
3  3  0  1

i1==NA時,我需要重新編碼i2==NA 我在下面嘗試但沒有運氣。

df %>%
  mutate(i2 = case_when(
    i1 == NA ~  NA_real_,
    TRUE ~ as.character(i2)))

Error in `mutate()`:
! Problem while computing `i2 = case_when(i1 == "NA" ~ NA_real_, TRUE ~ as.character(i2))`.
Caused by error in `` names(message) <- `*vtmp*` ``:
! 'names' attribute [1] must be the same length as the vector [0]

我想要的 output 看起來像這樣:

> df
  id i1 i2
1  1  1  1
2  2 NA  NA
3  3  0  1

這是一個選項:

t(apply(df, 1, \(x) if (any(is.na(x))) cumsum(x) else x))
#     id i1 i2
#[1,]  1  1  1
#[2,]  2 NA NA
#[3,]  3  0  1

這個想法是計算每一行的累計和,如果一行包含NA 如果項i中有NA ,則后續項i+1也將為NA (因為例如NA + 1 = NA )。 由於您的樣本數據df都是數字,我建議使用matrix (而不是data.frame )。 矩陣操作通常比data.frame (即list )操作更快。

關鍵假設:

  1. id不能是NA
  2. 這將基於每行i1中的NA替換i2中的NA

一個tidyverse的解決方案

出於幾個原因,我建議不要在這里使用tidyverse解決方案

  1. 您的數據是全數字的,因此matrix是比data.frame / tibble更合適的數據結構。
  2. dplyr / tidyr語法通常在列上高效運行; 一旦您想“按行”做事, dplyr (及其系列包)可能不是最好的方法(盡管dplyr::rowwise()只是引入了基於行號的分組)。

解決了這個問題,您就可以transpose問題了。

library(tidyverse)
df %>%
    transpose() %>%
    map(~ { if (is.na(.x$i1)) .x$i2 <- NA_real_; .x }) %>%
    transpose() %>%
    as_tibble() %>%
    unnest(everything())
## A tibble: 3 × 3
#     id    i1    i2
#  <dbl> <dbl> <dbl>
#1     1     1     1
#2     2    NA    NA
#3     3     0     1

一個簡單的作業能滿足你的要求嗎?

df$i2[is.na(df$i1)] <- NA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM