3

I would like to replace NA in a particular column with values from another column in same dataframe

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

I would like to replace NA in NewPrice with the values in column Price

I have referred this but it is not helping Replace empty values with value from other column in a dataframe

Have tried below one but not working

df$NewPrice <- ifelse(df$NewPrice == "", df$Price, df$NewPrice)
Anshul S
  • 281
  • 1
  • 5

2 Answers2

3

I would try with standard subsetting:

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

Out:

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
LyzandeR
  • 37,047
  • 12
  • 77
  • 87
2

tidyverse solution:

df %>% mutate(NewPrice=coalesce(NewPrice, Price))
January
  • 16,320
  • 6
  • 52
  • 74