将NA值替换为同一数据框中另一列的值

时间:2019-07-12 08:06:13

标签: r dataframe

我想用同一数据帧中另一列的值替换特定列中的NA

DF1:

Item    From    Price    Discount    NewPrice
 A     Delhi    100        .10         110
 A     Mumbai   200        .10         120
 A     Pune     150         NA          NA
 A     Nagpur   200        .10          NA

我想用Price列中的值替换NewPrice中的NA

我已经提到了这个问题,但这对Replace empty values with value from other column in a dataframe并没有帮助

尝试过以下一项但不起作用

df$NewPrice <- ifelse(df$NewPrice == "", df$Price, df$NewPrice)

2 个答案:

答案 0 :(得分:3)

我会尝试使用标准子集:

#subset the NAs of new price with the ones from price
df$NewPrice[is.na(df$NewPrice)] <- df$Price[is.na(df$NewPrice)]

出局:

df
#  Item   From Price Discount NewPrice
#1    A  Delhi   100      0.1      110
#2    A Mumbai   200      0.1      120
#3    A   Pune   150       NA      150
#4    A Nagpur   200      0.1      200

答案 1 :(得分:2)

tidyverse解决方案:

df %>% mutate(NewPrice=coalesce(NewPrice, Price))
相关问题