【发布时间】:2020-04-11 04:39:04
【问题描述】:
我正在尝试group_by,找到符合条件的行的第一次出现,并创建一个新列,其值基于从每个组中选择的行。
示例
这很容易用一个例子来演示。一个新列应该由
生成- 按 transaction_id 分组
- 寻找第一次出现的icecream_bool (= 1)(注意第二笔交易有两行符合这个条件,所以应该取第一笔)
- 使用“item”列中的值创建新列
我们从这个data.frame开始
df <- data.frame(
transaction_id=as.integer(c(1,1,1,2,2,2,2,2,3,3,3)),
item=as.character(c("crisps", "magnum", "gum",
"jerky", "cheese", "snickers", "ben&jerry", "magnum",
"halo", "crisps", "mars")),
icecream_bool=as.integer(c(0,1,0,
0,0,0,1,1,
1,0,0)),
stringsAsFactors = F
)
# transaction_id item icecream_bool
# 1 1 crisps 0
# 2 1 magnum 1
# 3 1 gum 0
# 4 2 jerky 0
# 5 2 cheese 0
# 6 2 snickers 0
# 7 2 ben&jerry 1
# 8 2 magnum 1
# 9 3 halo 1
# 10 3 crisps 0
# 11 3 mars 0
期望的输出
像这样生成 ice_cream 列
transaction_id item icecream_bool ice_cream
1 1 crisps 0 magnum
2 1 magnum 1 magnum
3 1 gum 0 magnum
4 2 jerky 0 ben&jerry
5 2 cheese 0 ben&jerry
6 2 snickers 0 ben&jerry
7 2 ben&jerry 1 ben&jerry
8 2 magnum 1 ben&jerry
9 3 halo 1 halo
10 3 crisps 0 halo
11 3 mars 0 halo
【问题讨论】: