Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NA values with value from another column in same dataframe [duplicate]

Tags:

dataframe

r

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)
like image 630
Anshul S Avatar asked Mar 13 '26 12:03

Anshul S


1 Answers

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
like image 93
LyzandeR Avatar answered Mar 15 '26 01:03

LyzandeR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!