R 将NA值替换为同一数据帧中另一列的值
我想用同一数据帧中另一列的值替换特定列中的NA DF1: 我想用Price列中的值替换NewPrice中的NA 我已经提到了这一点,但它没有帮助 试过一次以下但不起作用R 将NA值替换为同一数据帧中另一列的值,r,dataframe,R,Dataframe,我想用同一数据帧中另一列的值替换特定列中的NA DF1: 我想用Price列中的值替换NewPrice中的NA 我已经提到了这一点,但它没有帮助 试过一次以下但不起作用 df$NewPrice <- ifelse(df$NewPrice == "", df$Price, df$NewPrice) df$NewPrice我会尝试使用标准子集: #subset the NAs of new price with the ones from price df$NewPrice[is.na(df
df$NewPrice <- ifelse(df$NewPrice == "", df$Price, df$NewPrice)
df$NewPrice我会尝试使用标准子集:
#subset the NAs of new price with the ones from price
df$NewPrice[is.na(df$NewPrice)] <- df$Price[is.na(df$NewPrice)]
tidyverse解决方案:
df %>% mutate(NewPrice=coalesce(NewPrice, Price))
在你的链接帖子中尝试df$NewPrice,空值是一个空字符串”
,在你的例子中它是NA
,因此我们需要检查is.NA
,正如安德鲁在上面的评论中所示。它起作用了。谢谢@Andrew Baxter&zx8754
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
df %>% mutate(NewPrice=coalesce(NewPrice, Price))