使用R检测列中的模式 [英] Detect a pattern in a column with R

查看:57
本文介绍了使用R检测列中的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算一个人从一项工作转到另一项工作的次数。每当Job列具有此模式 1-> 0-> 1

I am trying to calculate how many times a person moved from one job to another. This can be calculated every time the Job column has this pattern 1 -> 0 -> 1.

在此示例中,它发生了一次旋转:

In this example, it happened one rotation:

Person Job
  A     1
  A     0
  A     1
  A     1

在另一个示例中,人B也有一个轮换。

In this another example, person B had one rotation as well.

Person Job
  A     1
  A     0
  A     1
  A     1
  B     1
  B     0
  B     0 
  B     1

有什么方法可以很好地按人员在新的旋转列中测量此模式? / p>

Whats would be a good approach to measure this pattern in a new column 'rotation', by person ?

    Person Job  Rotation
      A     1      0
      A     0      0
      A     1      1
      A     1      1
      B     1      0
      B     0      0
      B     0      0
      B     1      1


推荐答案

以下是带有 data.table

library(data.table)
setDT(df)[, Rotation := +(grepl("101", do.call(paste0,
                       shift(Job, 0:.N, fill = 0)))), Person]
df
#    Person Job Rotation
# 1:      A   1       0
# 2:      A   0       0
# 3:      A   1       1
# 4:      A   1       1
# 5:      B   1       0
# 6:      B   0       0
# 7:      B   0       0
# 8:      B   1       0
# 9:      C   0       0
#10:      C   1       0
#11:      C   0       0
#12:      C   1       1






A base R 选项为

f1 <- function(x) Reduce(paste0, x, accumulate = TRUE)
df$Rotation <- with(df, +grepl("101", ave(Job, Person, FUN = f1)))



数据



data

df <- data.frame(Person = rep(c("A", "B", "C"), each = 4L),
                 Job = as.integer(c(1,0,1,1,
                                    1,0,0,1,
                                    0,1,0,1)))

这篇关于使用R检测列中的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆