Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将NA值替换为同一数据帧中另一列的值_R_Dataframe - Fatal编程技术网

R 将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

我想用同一数据帧中另一列的值替换特定列中的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$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))