r语言中将两个向量合成一个向量,如何在R中的一个向量中累加增加值

I have a data set that looks like this

id name year job job2

1 Jane 1980 Worker 0

1 Jane 1981 Manager 1

1 Jane 1982 Manager 1

1 Jane 1983 Manager 1

1 Jane 1984 Manager 1

1 Jane 1985 Manager 1

1 Jane 1986 Boss 0

1 Jane 1987 Boss 0

2 Bob 1985 Worker 0

2 Bob 1986 Worker 0

2 Bob 1987 Manager 1

2 Bob 1988 Boss 0

2 Bob 1989 Boss 0

2 Bob 1990 Boss 0

2 Bob 1991 Boss 0

2 Bob 1992 Boss 0

Here, job2 denotes a dummy variable indicating whether a person was a Manager during that year or not. I want to do two things to this data set: first, I only want to preserve the row when the person became Boss for the first time. Second, I would like to see cumulative years a person worked as a Manager and store this information in the variable cumu_job2. Thus I would like to have:

id name year job job2 cumu_job2

1 Jane 1980 Worker 0 0

1 Jane 1981 Manager 1 1

1 Jane 1982 Manager 1 2

1 Jane 1983 Manager 1 3

1 Jane 1984 Manager 1 4

1 Jane 1985 Manager 1 5

1 Jane 1986 Boss 0 0

2 Bob 1985 Worker 0 0

2 Bob 1986 Worker 0 0

2 Bob 1987 Manager 1 1

2 Bob 1988 Boss 0 0

I have changed my examples and included the Worker position because this reflects more what I want to do with the original data set. The answers in this thread only works when there are only Managers and Boss in the data set - so any suggestions for making this work would be great. I'll be very much grateful!!

解决方案

Here is the succinct dplyr solution for the same problem.

NOTE: Make sure that stringsAsFactors = F while reading in the data.

library(dplyr)

dat %.%

group_by(name, job) %.%

filter(job != "Boss" | year == min(year)) %.%

mutate(cumu_job2 = cumsum(job2))

Output:

id name year job job2 cumu_job2

1 1 Jane 1980 Worker 0 0

2 1 Jane 1981 Manager 1 1

3 1 Jane 1982 Manager 1 2

4 1 Jane 1983 Manager 1 3

5 1 Jane 1984 Manager 1 4

6 1 Jane 1985 Manager 1 5

7 1 Jane 1986 Boss 0 0

8 2 Bob 1985 Worker 0 0

9 2 Bob 1986 Worker 0 0

10 2 Bob 1987 Manager 1 1

11 2 Bob 1988 Boss 0 0

Explanation

Take the dataset

Group by name and job

Filter each group based on condition

Add cumu_job2 column.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值