[英]R: How to recode values of a variable to NA for cases where another variable has a value of 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
)操作更快。
關鍵假設:
id
不能是NA
。i1
中的NA
替換i2
中的NA
。tidyverse
的解決方案出於幾個原因,我建議不要在這里使用tidyverse
解決方案
matrix
是比data.frame
/ tibble
更合適的數據結構。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.