首次根据号码出现的条件选择行 [英] select row based on the condition of number apparence for first time

查看:118
本文介绍了首次根据号码出现的条件选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查找定义的数字首次出现(例如2)的行吗?

I would like to find rows in which defined number appear (for example 2) for first time?

例如:

group <- c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b")
value <- c(1, 1, 2, 2, 1, 1, 2, 1, 2, 3)
GOAL <- c("FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE")
data <- data.frame(group, value, GOAL)
data

将在目标"列中显示结果. 谢谢您的提前帮助.

In the column "GOAL" would be the result. Thank you for your help in advance.

推荐答案

这种方式假定每个group至少具有一个2.尽管您的示例数据是按组排序的,但此处使用的方法并不依赖于此.

This way assumes each group has at least one 2. Although your sample data is ordered by group, the approach used here doesn't depend on this.

# given vector v, return vector of FALSEs, except at the first 2
f <- function(v) replace(logical(length(v)), which(v == 2)[1], TRUE)
transform(data, GOAL=as.logical(ave(value, group, FUN=f)))
#    group value  GOAL
# 1      a     1 FALSE
# 2      a     1 FALSE
# 3      a     2  TRUE
# 4      a     2 FALSE
# 5      a     1 FALSE
# 6      b     1 FALSE
# 7      b     2  TRUE
# 8      b     1 FALSE
# 9      b     2 FALSE
# 10     b     3 FALSE

如果要TRUE/FALSE,则必须调用as.logical,因为ave始终返回数字矢量.如果没有as.logical,您将得到0和1.

The call to as.logical is necessary if you want TRUE/FALSE, since ave always returns a numeric vector. Without as.logical, you get 0s and 1s.

这篇关于首次根据号码出现的条件选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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