R代码可基于多个变量分配序列 [英] R code to assign a sequence based off of multiple variables
本文介绍了R代码可基于多个变量分配序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据结构如下:
ID Day Desired Output
1 1 1
1 1 1
1 1 1
1 2 2
1 2 2
1 3 3
2 4 1
2 4 1
2 5 2
3 6 1
3 6 1
是否可以在不使用循环的情况下为所需的输出创建序列?该数据集非常大,因此无法使用循环,是否可以使用dplyr软件包或cumsum/diff的组合来做到这一点?
Is it possible to create a sequence for the desired output without using a loop? The dataset is quite large so a loop won't work, is it possible to do this with the dplyr package or maybe a combination of cumsum/diff?
推荐答案
一个选项是按'ID'分组,然后在'Day'上使用'Day'列的unique
值进行match
An option is to group by 'ID', and then do a match
on the 'Day' with the unique
values of 'Day' column
library(dplyr)
df1 %>%
group_by(ID) %>%
mutate(desired = match(Day, unique(Day)))
数据
df1 <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L), Day = c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L, 5L, 6L, 6L)), row.names = c(NA,
-11L), class = "data.frame")
这篇关于R代码可基于多个变量分配序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文