如何根据不同行中存在的值为NA填充零- R

z9smfwbn  于 2023-05-26  发布在  其他
关注(0)|答案(2)|浏览(155)

我有一个DF,如下所示。数据框显示了每次访视时每个研究中心的捕获和重新捕获数量。然而,每个研究中心和捕获类型的访问次数并不相同。因此,简单地将所有NA转换为零没有意义。我想要的是将NA转换为零,用于存在捕获数据的重新捕获站点。
例如,网站“admin_pond”被访问了3次,捕获类型为“new”,每次都有捕获。对于“admin_pond”捕获类型“recapture”,只有visit_3具有recapture。因此,对于“admin_pond”/“recapture”的visit_1和visit_2,我希望用零填充NA。但是仍然保持visit_4、visit_5和visit_6作为“admin_pond”/“recapture”的NA。如何对所有站点执行此操作并重新捕获观察结果?

数据

data <- structure(list(site = c("wood_lab_pond", "phelps_pond", "admin_pond", 
"rv_pond", "admin_pond", "wood_lab_pond", "rv_pond", "tuttle_pond", 
"tuttle_pond", "vorisek_pond", "vorisek_pond", "phelps_pond"), 
    capture_type = c("new", "new", "new", "new", "recapture", 
    "recapture", "recapture", "new", "recapture", "new", "recapture", 
    "recapture"), visit_1 = c(2L, 4L, 9L, 1L, NA, NA, NA, 15L, 
    NA, 14L, NA, NA), visit_2 = c(4L, 3L, 15L, 7L, NA, NA, NA, 
    12L, 10L, 4L, 9L, NA), visit_3 = c(1L, 6L, 11L, 4L, 9L, 2L, 
    1L, 39L, NA, NA, NA, NA), visit_4 = c(NA, NA, NA, 13L, NA, 
    NA, NA, 21L, 10L, NA, NA, NA), visit_5 = c(NA, NA, NA, 27L, 
    NA, NA, 2L, 27L, 2L, NA, NA, NA), visit_6 = c(NA, NA, NA, 
    11L, NA, NA, NA, 19L, 1L, NA, NA, NA)), row.names = c(NA, 
-12L), class = c("tbl_df", "tbl", "data.frame"))
pgccezyw

pgccezyw1#

我想用{tidyverse}可以很容易地解决。我会这样做:

library(tidyverse)

data <- data %>% 
  group_by(site) %>% 
  arrange(site, capture_type) %>% # It is not required
  mutate(across(contains("visit"), 
                ~ifelse(is.na(.) &
                          !is.na(lag(.)), 0, .)))

此代码返回following dataframe

inn6fuwd

inn6fuwd2#

这里假设每个站点正好有2行,一行new和一行recapture

data |>
  arrange(site, capture_type) |>
  mutate(
    across(starts_with("visit"),
      \(x) coalesce(x, ifelse(!is.na(lag(x, default = 0)), 0, NA_integer_))
    ),
    .by = site
  )
# # A tibble: 12 × 8
#    site          capture_type visit_1 visit_2 visit_3 visit_4 visit_5 visit_6
#    <chr>         <chr>          <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
#  1 admin_pond    new                9      15      11      NA      NA      NA
#  2 admin_pond    recapture          0       0       9      NA      NA      NA
#  3 phelps_pond   new                4       3       6      NA      NA      NA
#  4 phelps_pond   recapture          0       0       0      NA      NA      NA
#  5 rv_pond       new                1       7       4      13      27      11
#  6 rv_pond       recapture          0       0       1       0       2       0
#  7 tuttle_pond   new               15      12      39      21      27      19
#  8 tuttle_pond   recapture          0      10       0      10       2       1
#  9 vorisek_pond  new               14       4      NA      NA      NA      NA
# 10 vorisek_pond  recapture          0       9      NA      NA      NA      NA
# 11 wood_lab_pond new                2       4       1      NA      NA      NA
# 12 wood_lab_pond recapture          0       0       2      NA      NA      NA

相关问题