根据R中的条件合并列

问题描述 投票:0回答:1

我想合并两个列,lat.x和lat.y,所以我得到一个新列lat。

数据:

lat.x    lat.y    lat
  1        1       1
  2        2       2
 NA        3       3
  4        NA      4
  5        6       5

我试过了:

df2$Lat <- ifelse(df$Lat.x == "NA", df$Lat.y, df$Lat.x)
r if-statement merge
1个回答
1
投票

如果x == "NA"是一个字符为x的文字字符串,则无法使用"NA"测试NA。相反,你应该使用基本函数is.na()

这有效:

df <- data.frame(
  lat.x = c(1, 2, NA, 4, 5),
  lat.y = c(1, 2, 3, NA, 5)
)

df$lat <- ifelse(is.na(df$lat.x), df$lat.y, df$lat.x)

此外,您应该考虑以可复制粘贴的格式提供示例数据(就像我上面所做的那样)。这样可以更轻松地测试代码并提供答案。

© www.soinside.com 2019 - 2024. All rights reserved.