我有一个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"))
2条答案
按热度按时间pgccezyw1#
我想用{tidyverse}可以很容易地解决。我会这样做:
此代码返回following dataframe
inn6fuwd2#
这里假设每个站点正好有2行,一行
new
和一行recapture
: