I have a shapefile that has multiple columns, and I am trying to merge columns X5
andX1
into a new column class
, such that only the NA
rows of X5
get filled by the corresponding rows of X1
. For example, in the new column the rows 1-4
will have values from rows 1-4
of X5
, but rows 5-7
will have value GRND
from column X1
. Similarly, then rows 8-9
of column class
will be filled with values PLSE
from X5
and so. Hope it makes sense. How can I do this in R
. I am thinking of using dplyr
and ifelse
, but I am stuck.
Sample data
FID X1 X5 class
1 VEG PRPU
2 VEG PRPU
3 VEG PRPU
4 VEG PRPU
5 WTR NA
6 WTR NA
7 WTR NA
8 VEG PLSE
9 VEG PLSE
10 GRND NA
11 GRND NA
Code
library(sf)
library(tidyverse)
# Load shapefile
shp = st_read("path", "filename")
# Create a new column class
shp %>% add_column(class = NA)
# Try
shp %>% mutate(class = ifelse(class %in% "", X5, class)) # Stuck...
2 Answers 2
You were really close. You should use ==
instead of %in%
.
shp %>%
mutate(class = ifelse(is.na(X5), X1, X5))
# FID X1 X5 class
#1 1 VEG PRPU PRPU
#2 2 VEG PRPU PRPU
#3 3 VEG PRPU PRPU
#4 4 VEG PRPU PRPU
#5 5 WTR WTR
#6 6 WTR WTR
#7 7 WTR WTR
#8 8 VEG PLSE PLSE
#9 9 VEG PLSE PLSE
#10 10 GRND GRND
#11 11 GRND GRND
-
I am getting
NA
values where there were supposed to beX1
values in theclass
column.Arthur_Morgan– Arthur_Morgan2021年07月15日 23:17:52 +00:00Commented Jul 15, 2021 at 23:17 -
1Try checking if there are
X5
entries filled with a blank space or something like that. That is probably causing those results.Jonathan V. Solórzano– Jonathan V. Solórzano2021年07月16日 01:00:07 +00:00Commented Jul 16, 2021 at 1:00 -
Yes you are right thank you, the empty rows shown in
ArcGIS
were actually being shown asNA
inR
. So doing,shp %>% dplyr::mutate(class = ifelse(is.na(X5), X1, X5))
fixes the issue. You can edit that in your answer to reflect that.Arthur_Morgan– Arthur_Morgan2021年07月16日 01:19:46 +00:00Commented Jul 16, 2021 at 1:19
If the only issue is to resolve NAs, and you are using {dplyr}
anyhow, you may consider dplyr::coalesce()
for a somewhat more concise code.
library(dplyr)
shp <- tibble::tribble(~FID, ~X1, ~X5,
1, 'VEG', 'PRPU',
2, 'VEG', 'PRPU',
3, 'VEG', 'PRPU',
4, 'VEG', 'PRPU',
5, 'WTR', NA,
6, 'WTR', NA,
7, 'WTR', NA,
8, 'VEG', 'PLSE',
9, 'VEG', 'PLSE',
10, 'GRND', NA,
11, 'GRND', NA)
shp %>%
mutate(class = coalesce(X5, X1))
FID X1 X5 class
<dbl> <chr> <chr> <chr>
1 1 VEG PRPU PRPU
2 2 VEG PRPU PRPU
3 3 VEG PRPU PRPU
4 4 VEG PRPU PRPU
5 5 WTR NA WTR
6 6 WTR NA WTR
7 7 WTR NA WTR
8 8 VEG PLSE PLSE
9 9 VEG PLSE PLSE
10 10 GRND NA GRND
11 11 GRND NA GRND