3

我正在尝试使用 R 程序将 SpatialDataFrame (shapefile) 的两列合并为一列,但是在两列中都有空格,当它们与名称加 NA 一起时,但是我希望 NA 不会出现在我的新专栏。我使用了粘贴功能。像这样的东西:

  This is the structure of my SpatialDataFrame:


  ID           city                city2
1  1      saõ paulo                 <NA>
2  2      Rio de Janeiro            <NA>
3  3           <NA>            Belo Horizonte
4  4           <NA>            Curitiba

obs。我的原始数据不是这个并且有更多的列

我用这个:

data$newCity <- paste(data$city, data$city2) # I don't want to show in my data Na

1.

ID          city          city2                newCity
  1      saõ paulo         <NA>            saõ paulo NA
  2  Rio de Janeiro        <NA>            Rio de Janeiro NA
  3        <NA>       Belo Horizonte       NA Belo Horizonte
  4        <NA>       Curitiba             NA Curitiba

事实上,这将是期望的结果:

ID          city          city2                 newCity
 1      saõ paulo         <NA>                saõ paulo
 2    Rio de Janeiro      <NA>               Rio de Janeiro
 3        <NA>         Belo Horizonte         Belo Horizonte
 4        <NA>          Curitiba              Curitiba
4

4 回答 4

2

另一种base R选择可能是:

with(df, pmax(city, city2, na.rm = TRUE))

[1] "sao paulo"      "rio de janeiro" "Belo Horizonte" "Curitiba" 
于 2020-03-04T19:03:56.430 回答
1

使用paste将字符列粘合在一起,用空格分隔,即“_”。尝试这个:

data$newCity <- ifelse(is.na(data$city), data$city2, data$city)
于 2020-03-04T18:57:39.873 回答
1

您可以unite()使用tidyr

library(tidyr)

df %>%
  unite(newCity, city:city2, remove = F, na.rm = T)

该参数na.rm = T仅适用于字符列。

于 2020-03-04T19:02:34.247 回答
0

您可以使用包中的coalesce功能dplyr

df <- data.frame(ID = 1:4,
                 city = c("sao paulo", "rio de janeiro", NA, NA),
                 city2 = c(NA, NA, "Belo Horizonte", "Curitiba"), stringsAsFactors = FALSE)


library(dplyr)
df %>% mutate(City = coalesce(city, city2))
  ID           city          city2           City
1  1      sao paulo           <NA>      sao paulo
2  2 rio de janeiro           <NA> rio de janeiro
3  3           <NA> Belo Horizonte Belo Horizonte
4  4           <NA>       Curitiba       Curitiba
于 2020-03-04T19:01:30.193 回答