在R中的数据帧中添加频率列

时间:2014-03-17 18:33:39

标签: r count dataframe frequency

我有一个名为" Drink"的数据报,它有以下单元格。 我想添加一个部分百分比列。

| Part# | Order  | Name  |  Time |
-------------------------------------------------
| AAAA | 00001  | APPL  |  2 PM |
--------------------------------------------------
| BBBB | 00002  | BEER  |  5 PM |
-------------------------------------------------
| CCCC | 00003  | COKE  |  3 PM |
--------------------------------------------------
| AAAA | 00004  | APPL  |  9 AM |
--------------------------------------------------
| AAAA | 00005  | APPL  |  7 PM |
--------------------------------------------------
| BBBB | 00006  | BEER  |  3 AM |
--------------------------------------------------

PERCENTAGE列是(购买的零件的频率/总的唯一订单)

我尝试做的结果表是这样的:

| Part# | Order  | Name  |  Time | PERCENTAGE |
-------------------------------------------------
| AAAA | 00001  | APPL  |  2 PM |  3/6 or 50%
--------------------------------------------------
| BBBB | 00002  | BEER  |  5 PM |  2/6 or 33%
-------------------------------------------------
| CCCC | 00003  | COKE  |  3 PM |  1/6 or 17%
--------------------------------------------------
| AAAA | 00004  | APPL  |  9 AM |  3/6 or 50%
--------------------------------------------------
| AAAA | 00005  | APPL  |  7 PM |  3/6 or 50%
--------------------------------------------------
| BBBB | 00006  | BEER  |  3 AM |  2/6 or 33%
--------------------------------------------------

1 个答案:

答案 0 :(得分:0)

这样的事情(顺便说一句,您的数据结构并不是最好的;我会使用dputhead并将其粘贴到数据中):

set.seed(10)
dat <- CO2[sample(1:nrow(CO2), 10), 5:1]

funny <- function(x) {
    sprintf("%s/%s or %s%%", length(x), nrow(dat), 100*length(x)/nrow(dat))
}

dat$PERCENTAGE <- ave(as.character(dat$Plant), dat$Plant, FUN=funny)

dat

##    uptake conc  Treatment        Type Plant  PERCENTAGE
## 43   10.6   95 nonchilled Mississippi   Mn1 2/10 or 20%
## 26   32.5  500    chilled      Quebec   Qc1 2/10 or 20%
## 36   15.1   95    chilled      Quebec   Qc3 1/10 or 10%
## 57   11.3   95 nonchilled Mississippi   Mn3 1/10 or 10%
## 7    39.7 1000 nonchilled      Quebec   Qn1 1/10 or 10%
## 18   42.1  350 nonchilled      Quebec   Qn3 2/10 or 20%
## 22   14.2   95    chilled      Quebec   Qc1 2/10 or 20%
## 21   45.5 1000 nonchilled      Quebec   Qn3 2/10 or 20%
## 47   30.9  500 nonchilled Mississippi   Mn1 2/10 or 20%
## 33   38.6  500    chilled      Quebec   Qc2 1/10 or 10%