用 R 中另一列的值替换值 NA [英] Replace a value NA with the value from another column in R

查看:37
本文介绍了用 R 中另一列的值替换值 NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to replace the NA value in dfABy from the column A, with the value from the column B, based on the year of column year. For example, my df is:

                 >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

P.S: 用 * 替换每年 B 列 A 列中的值

P.S: with the * the value replacing in column A from column B for every year

推荐答案

也许 R 词典中最容易阅读/理解的答案是使用 ifelse.因此,我们可以借用 Richard 的数据框:

Perhaps the easiest to read/understand answer in R lexicon is to use ifelse. So borrowing Richard's dataframe we could do:

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)

这篇关于用 R 中另一列的值替换值 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆