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

Die*_*ego 18 replace r na

我想根据列年份的年份将 A 列中 dfABy 中的 NA 值替换为 B 列中的值。例如,我的 df 是:

                 >dfABy 
                 A    B   Year
                 56   75  1921
                 NA   45  1921
                 NA   77  1922
                 67   41  1923
                 NA   65  1923
Run Code Online (Sandbox Code Playgroud)

我参加的结果是:

                 > dfABy
                 A    B   Year
                 56   75  1921
                *45*  45  1921
                *77*  77  1922
                 67   41  1923
                *65*  65  1923
Run Code Online (Sandbox Code Playgroud)

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

JHo*_*wIX 25

也许 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)
Run Code Online (Sandbox Code Playgroud)


GGA*_*son 18

现在根据@Max 进行更正。 (最初与初始实现一起工作)

新的 dplyr 函数coalesce可以真正简化这些情况。

library(dplyr)

dfABy %>% 
    mutate(A = coalesce(A,B))
Run Code Online (Sandbox Code Playgroud)


小智 15

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
Run Code Online (Sandbox Code Playgroud)

(我是 Stackoverflow 的新手;我的低声誉不允许直接评论 GGAnderson 的回答)


bra*_*ayl 5

简单的

library(dplyr)

dfABy %>%
  mutate(A_new = 
           A %>% 
             is.na %>%
             ifelse(B, A) )
Run Code Online (Sandbox Code Playgroud)


Ric*_*ven 5

您可以使用[<-, 对NA元素进行简单替换。

df$A[is.na(df$A)] <- df$B[is.na(df$A)]
Run Code Online (Sandbox Code Playgroud)

或者, within()

within(df, A[is.na(A)] <- B[is.na(A)])
Run Code Online (Sandbox Code Playgroud)

都给

   A  B Year
1 56 75 1921
2 45 45 1921
3 77 77 1922
4 67 41 1923
5 65 65 1923
Run Code Online (Sandbox Code Playgroud)

数据:

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))
Run Code Online (Sandbox Code Playgroud)