繁体   English   中英

将一列中的值添加到另一列中的值

[英]Adding values from one column to values in another

我正在计算我测量的树木的新直径,方法是获取它们的初始直径(2018 年拍摄),然后加上 2020 年和 2021 年的直径增长厘米数 (diam_growth)。这将填写列中的 NA “dbh”。 这里有一些示例数据可以帮助解释

tag <- c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4)
diam_growth <- c(0.4, 0.5, NA, 0.7, 0.8, NA, 0.9, 1.0, NA, 0.1, 0.2, NA)
dbh <- c(NA, NA, 10, NA, NA, 15, NA, NA, 7, NA, NA, 12)
year <- c(2020, 2021, 2018, 2020, 2021, 2018, 2020, 2021, 2018, 2020, 2021, 2018)

tree_growth <- data.frame(tag, diam_growth, dbh, year)

   tag diam_growth dbh year
1    1         0.4  NA 2020
2    1         0.5  NA 2021
3    1          NA  10 2018
4    2         0.7  NA 2020
5    2         0.8  NA 2021
6    2          NA  15 2018
7    3         0.9  NA 2020
8    3         1.0  NA 2021
9    3          NA   7 2018
10   4         0.1  NA 2020
11   4         0.2  NA 2021
12   4          NA  12 2018

因此,例如,对于标签 1,代码将采用 2018 年的 dbh (10) 并为 2020 年添加 0.4,为 2021 年添加 0.5。然后对于标签 2,它将分别为 2020 年和 2021 年的初始 DBH 15 添加 0.7 和 0.8依此类推每个标签 ID。

按“标签”分组,通过将值与“dbh”中的非 NA 值相加, replace “dbh”中为NA的“diam_growth”值

library(dplyr)
tree_growth %>% 
   group_by(tag) %>%
    mutate(diam_growth  = replace(diam_growth, is.na(dbh), 
        diam_growth[is.na(dbh)] + dbh[!is.na(dbh)])) %>%
   ungroup

-输出

# A tibble: 12 × 4
     tag diam_growth   dbh  year
   <dbl>       <dbl> <dbl> <dbl>
 1     1        10.4    NA  2020
 2     1        10.5    NA  2021
 3     1        NA      10  2018
 4     2        15.7    NA  2020
 5     2        15.8    NA  2021
 6     2        NA      15  2018
 7     3         7.9    NA  2020
 8     3         8      NA  2021
 9     3        NA       7  2018
10     4        12.1    NA  2020
11     4        12.2    NA  2021
12     4        NA      12  2018

或者使用case_when

tree_growth %>% 
   group_by(tag) %>% 
   mutate(diam_growth = case_when(is.na(dbh) ~ diam_growth + 
         dbh[!is.na(dbh)], TRUE ~ diam_growth)) %>% 
   ungroup

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM