我目前有一个类似于多个ID的数据(范围直到1600左右)
id year name status
1 1980 James 3
1 1981 James 3
1 1982 James 3
1 1983 James 4
1 1984 James 4
1 1985 James 1
1 1986 James 1
1 1987 James 1
2 1982 John 2
2 1983 John 2
2 1984 John 1
2 1985 John 1
Run Code Online (Sandbox Code Playgroud)
我希望对这些数据进行子集化,以便它只有status = 1的信息和之前的状态.我也想消除多个1,只保存前1个.总之,我想要:
id year name status
1 1984 James 4
1 1985 James 1
2 1983 John 2
2 1984 John 1
Run Code Online (Sandbox Code Playgroud)
我这样做是因为我正在弄清楚在哪一年有多少人从某个状态变为状态1.我只知道子集命令,我不认为我可以从中做这些数据subset(data, subset=(status==1)).我怎么能在那之前保存信息
我想再次添加这个问题 - 当我对这个问题(使用plr包)的第一个回复和使用重复命令的第三个回复应用时,我没有得到相同的结果.我发现第一个回复准确地保留了信息,而第三个回复没有.
这就是你想要的。
library(plyr)
ddply(d, .(name), function(x) {
i <- match(1, x$status)
if (is.na(i))
NULL
else
x[c(i-1, i), ]
})
id year name status
1 1 1984 James 4
2 1 1985 James 1
3 2 1983 John 2
4 2 1984 John 1
Run Code Online (Sandbox Code Playgroud)