[英]Create a new column based on the sum of values from another column, with dplyr
我想創建一個名為 POPULATION 的新變量,它占用由變量 CODASC 分組的變量 P1 的值的總和。 一開始對我來說似乎很容易,但我最終在掙扎。 由於我必須對許多變量和多個數據集執行此操作,因此我真的需要一種快速的方法! 如果有人可以幫助我,我將不勝感激! 非常感謝,伊拉里亞
我的數據框看起來像這樣:
PROCOM SEZ2011 SEZ CODASC P1 P47 P62 P131 E1 E3 ST15 A46
<int> <dbl> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 48017 480000000000 60001 4 251 25 9 20 70 40 19 20
2 48017 480000000000 60002 3 15 1 0 1 4 4 0 3
3 48017 480000000000 60003 2 20 7 2 1 1 1 1 1
4 48017 480000000000 60004 3 253 21 4 10 63 40 49 22
5 48017 480000000000 60005 5 3 0 1 0 1 1 0 2
6 48017 480000000000 60006 1 161 19 7 5 27 17 26 13
>
我的代碼看起來像這樣:
df <- df %>%
group_by(CODASC) %>%
mutate(POPULATION = sum(P1 , na.rm= T))
要跨多個變量應用組內的總和,您可以執行以下操作,例如:
library(dplyr)
df %>%
group_by(CODASC) %>%
mutate(across(P1:last_col(), sum, .names = "{.col}_sum")) %>%
ungroup()
要將其應用於多個數據框(如果您按相同的變量分組並對相同的列求和),如果它們在列表中並使用purrr
庫,您可以輕松地遍歷它們:
library(purrr)
library(dplyr)
l <- list(df, df, df)
map(l, ~ .x %>%
group_by(CODASC) %>%
mutate(across(P1:last_col(), sum, .names = "{.col}_sum")) %>%
ungroup())
您的代碼看起來像您想要的那樣,但您只是在尋找一種將其簡化為多列的方法?
看起來您的前 4 列是一些標識符。 如果要匯總所有剩余的列,可以執行以下操作:
df <- df %>%
group_by(PROCOM, SEZ2011, SEZ, CODASC) %>%
summarise_all(sum) ## or whatever function you want here
有關summarise_all()
或summarise_at()
更多詳細信息,請參閱https://dplyr.tidyverse.org/reference/summarise_all.html 。
如果你想創建一個函數來應用於許多數據集,也許可以查看制作函數: https : //swcarpentry.github.io/r-novice-inflammation/02-func-R/並應用函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.