[英]Calculating category specific variable in R
我有大數據,col_1 為第一類,col_2 為第二類。 我附上一個樣本表格(參考下圖)。 數據有前四列(col_1、col_2、ice、fd)。 我想通過將列 fd 的總和作為分母,將不同 col_2 的“ice”的值作為分子並將它們相加,為 col_1 的每個類別生成變量“ice_new”。 我嘗試在 R 中使用“聚合”函數,但它不起作用。 我如何在 R 中執行它? 任何幫助將不勝感激
col_1 col_2 ice fd ice_new
A A1 0.3 0.1 (0.3/(0.1+0.4) + 0.2/(0.1+0.4)
A A2 0.2 0.4 (0.3/(0.1+0.4) + 0.2/(0.1+0.4)
B B1 1.2 1 1.2/(1+2+1.2) + 1.4/(1+2+1.2) + 0.6/ (1+2+1.2)
B B2 1.4 2 1.2/(1+2+1.2) + 1.4/(1+2+1.2) + 0.6/ (1+2+1.2)
B B3 0.6 1.2 1.2/(1+2+1.2) + 1.4/(1+2+1.2) + 0.6/ (1+2+1.2)
一種dplyr
可能性可能是:
df %>%
group_by(col_1) %>%
mutate(ice_new = sum(ice/sum(fd)))
col_1 col_2 ice fd ice_new
<chr> <chr> <dbl> <dbl> <dbl>
1 A A1 0.3 0.1 1
2 A A2 0.2 0.4 1
3 B B1 1.2 1 0.762
4 B B2 1.4 2 0.762
5 B B3 0.6 1.2 0.762
或與base R
相同:
with(df, ave(ice/ave(fd, col_1, FUN = sum), col_1, FUN = sum))
df1 <- data.frame("col_1" = c("A", "A", "B", "B", "B"),
"col_2" = c("A1", "A2", "B1", "B2", "B3"),
"ice" = c(.3,.2,1.2,1.4,.6),
"fd" = c(.1,.4,1,2,1.2))
library(dplyr)
df2 <- df1 %>%
group_by(col_1) %>%
mutate(ice_new=sum(ice)/sum(fd))
df2
## A tibble: 5 x 5
## Groups: col_1 [2]
# col_1 Col_2 ice fd ice_new
# <fct> <fct> <dbl> <dbl> <dbl>
#1 A A1 0.3 0.1 1
#2 A A2 0.2 0.4 1
#3 B B1 1.2 1 0.762
#4 B B2 1.4 2 0.762
#5 B B3 0.6 1.2 0.762
您還可以使用 summary 為每組獲取一個值:
library(dplyr)
df %>%
group_by(col_1) %>%
summarise(ice_new = sum(ice / sum(fd)))
# A tibble: 2 x 2
col1 ice_new
<chr> <dbl>
1 A 1
2 B 0.762
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.