簡體   English   中英

用 R 中另一列的值替換值 NA

[英]Replace a value NA with the value from another column in R

我想根據列年份的年份將 A 列中 dfABy 中的 NA 值替換為 B 列中的值。 例如,我的 df 是:

                 >dfABy 
                 A    B   Year
                 56   75  1921
                 NA   45  1921
                 NA   77  1922
                 67   41  1923
                 NA   65  1923

我參加的結果是:

                 > dfABy
                 A    B   Year
                 56   75  1921
                *45*  45  1921
                *77*  77  1922
                 67   41  1923
                *65*  65  1923

PS:用 * 替換 A 列中 B 列中每年的值

也許 R 詞典中最容易閱讀/理解的答案是使用 ifelse。 所以借用理查德的數據框,我們可以這樣做:

df <- structure(list(A = c(56L, NA, NA, 67L, NA),
                     B = c(75L, 45L, 77L, 41L, 65L),
                     Year = c(1921L, 1921L, 1922L, 1923L, 1923L)),.Names = c("A", 
                                                                                                                            "B", "Year"), class = "data.frame", row.names = c(NA, -5L))
df$A <- ifelse(is.na(df$A), df$B, df$A)

現在根據@Max 進行更正。 (最初與初始實現一起工作)

新的 dplyr 函數coalesce可以真正簡化這些情況。

library(dplyr)

dfABy %>% 
    mutate(A = coalesce(A,B))

GGAnderson 提供的解決方案確實返回了錯誤消息。 但是在 mutate() 中使用它效果很好。

df <- structure(list(A = c(56L, NA, NA, 67L, NA),
                     B = c(75L, 45L, 77L, 41L, 65L),
                     Year = c(1921L, 1921L, 1922L, 1923L, 1923L)),
                .Names = c("A", "B", "Year"), 
                class = "data.frame", 
                row.names = c(NA, -5L))
df
df%>% 
  coalesce(A,B) #returns error

df %>%
mutate(A = coalesce(A,B)) #works

(我是 Stackoverflow 的新手;我的低聲譽不允許直接評論 GGAnderson 的回答)

您可以使用[<-簡單替換,為NA元素設置子集。

df$A[is.na(df$A)] <- df$B[is.na(df$A)]

或者, within()

within(df, A[is.na(A)] <- B[is.na(A)])

都給

   A  B Year
1 56 75 1921
2 45 45 1921
3 77 77 1922
4 67 41 1923
5 65 65 1923

數據:

df <- structure(list(A = c(56L, NA, NA, 67L, NA), B = c(75L, 45L, 77L, 
41L, 65L), Year = c(1921L, 1921L, 1922L, 1923L, 1923L)), .Names = c("A", 
"B", "Year"), class = "data.frame", row.names = c(NA, -5L))

簡單

library(dplyr)

dfABy %>%
  mutate(A_new = 
           A %>% 
             is.na %>%
             ifelse(B, A) )

暫無
暫無

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

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