I've a dataframe like that
Polygon_No shp Sp. area
2 4 T.a. 31429.
2 4 T.n. 0
2 6 B.a. 0
2 6 T.a. 15714.
I want to replace the 0 in area column with value in the same column
I mean if area == 0 & shp cell values matches (6&6) & Polygon_No (2&2) replace 0 with 15714.
CodePudding user response:
I'd prefer max
and dplyr::group_by
with dplyr::mutate
:
df %>% group_by(Polygon_No, shp) %>%
mutate(area=max(area))
Output:
Polygon_No shp Sp. area
<int> <int> <chr> <dbl>
1 2 4 T.a. 31429
2 2 4 T.n. 31429
3 2 6 B.a. 15714
4 2 6 T.a. 15714
CodePudding user response:
You may try
library(dplyr)
df %>%
group_by(Polygon_No, shp) %>%
mutate(area = ifelse(area>0, area, NA)) %>%
mutate(area = unique(area[!is.na(area)]))
Polygon_No shp Sp. area
<int> <int> <chr> <dbl>
1 2 4 T.a. 31429
2 2 4 T.n. 31429
3 2 6 B.a. 15714
4 2 6 T.a. 15714