簡體   English   中英

如何按特定的列值拆分數據幀,然后將函數應用於數據集中的列?

[英]How do I split a data frame by a specific column value, and then apply functions to columns within the data set?

我有一個包含3列描述帳戶的數據框:

年齡,使用者和費用

“年齡”列的范圍是1到20,我想做的是按年齡計算平均費用,然后按年齡划分“平均用戶數”。

因此,例如,年齡均為1的平均用戶數是多少,年齡為1的平均帳戶成本是多少。

數據框很大,我不希望僅輸入df = data [data $ age_month == 1],然后將均值乘以1到列。

Age  Users   Cost
1     2       5
2     15      7
2     124     10
2     43      100
3     232     21212
4     234     21212 
4     12      10000 
4     10      3
5     11      89
6     4       11
6     8       12
6     10      15

因此,我希望將“年齡= 1”的“均值成本”列除以“年齡= 1”以及所有年齡段的“用戶均值”列

提前致謝,

嘗試:

CostbyAge <- with(dat, ave(Cost, Age, FUN=mean) )
UsersbyAge <- with(dat, ave(Users, Age, FUN=mean))
CostbyAge/UsersbyAge
# [1]   2.5000000   0.6428571   0.6428571   0.6428571  91.4310345 121.9335938
# [7] 121.9335938 121.9335938   8.0909091   1.7272727   1.7272727   1.7272727

這是使用doBy::summaryBy 假設dat是您的樣本數據

> library(doBy)
> ( s <- summaryBy(Users+Cost~Age, data = dat) )
#   Age Users.mean   Cost.mean
# 1   1   2.000000     5.00000
# 2   2  60.666667    39.00000
# 3   3 232.000000 21212.00000
# 4   4  85.333333 10405.00000
# 5   5  11.000000    89.00000
# 6   6   7.333333    12.66667
> s$Cost.mean / s$Users.mean
# [1]   2.5000000   0.6428571  91.4310345 121.9335938   8.0909091   1.7272727

這是使用dplyr的一種方法:

library(dplyr)

dat %>%
  group_by(Age) %>%
  summarize(count=length(Age),
            users_mean=round(mean(Users),2),
            cost_mean=round(mean(Cost),2),
            cost_per_user=round(cost_mean/users_mean,2))

  Age count users_mean cost_mean cost_per_user
1   1     1       2.00      5.00          2.50
2   2     3      60.67     39.00          0.64
3   3     1     232.00  21212.00         91.43
4   4     3      85.33  10405.00        121.94
5   5     1      11.00     89.00          8.09
6   6     3       7.33     12.67          1.73

data.table解決方案

library(data.table)
setDT(dat)[, list(User_mean = mean(Users), 
                  Mean_Cost = mean(Cost), 
                  Cost_per_User = mean(Cost)/mean(Users)), by = Age]

基本R,使用aggregate

aggdat <- aggregate(cbind(Users, Cost) ~ Age, dat,  mean)
aggdat$Cost_per_User <- aggdat$Cost/aggdat$Users

由於沒有人提及,因此您還可以將base R splitlapply結合使用:

> lapply(split(dat,dat$Age),colMeans)

要將結果輸出為數據框而不是列表,將需要以下附加步驟:

> do.call(rbind,lapply(split(dat,dat$Age),colMeans))
  Age      Users        Cost
1   1   2.000000     5.00000
2   2  60.666667    39.00000
3   3 232.000000 21212.00000
4   4  85.333333 10405.00000
5   5  11.000000    89.00000
6   6   7.333333    12.66667

split取數據框並創建一個相應的數據lapply列表,然后通過lapply對所有子數據lapply進行操作(此處計算平均值,您可以簡單地使用colMeans )。 然后do.call(rbind,...)獲取結果列表,並將其返回到數據框。

獲得每位用戶成本的最后一步與其他解決方案相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM