Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将数据框中的行标记为“;“真的”;如果出现组内的特定编号_R_Select_Row_Conditional Statements - Fatal编程技术网

R 将数据框中的行标记为“;“真的”;如果出现组内的特定编号

R 将数据框中的行标记为“;“真的”;如果出现组内的特定编号,r,select,row,conditional-statements,R,Select,Row,Conditional Statements,我以前问过你类似的问题,现在改一下,反之亦然? 我想在组中查找定义的编号最后一次出现的行,但如果该编号没有出现在组中,则将使用下一个最高编号 数据如下所示: group <- c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "c") value <- c(1, 3, 2, 1, 1, 1, 2, 1, 2, 3, 3, 2) dat <- data.frame(group, value) dat group给你

我以前问过你类似的问题,现在改一下,反之亦然? 我想在组中查找定义的编号最后一次出现的行,但如果该编号没有出现在组中,则将使用下一个最高编号

数据如下所示:

group <- c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "c")
value <- c(1, 3, 2, 1, 1, 1, 2, 1, 2, 3, 3, 2)
dat <- data.frame(group, value)
dat
group给你

f <- function(v) replace(logical(length(v)), 
                         which(v == max(v) & !duplicated(v, fromLast=TRUE)), 
                         TRUE)
transform(dat, GOAL=as.logical(ave(value, group, FUN=f)))
#    group value  GOAL
# 1      a     1 FALSE
# 2      a     3  TRUE
# 3      a     2 FALSE
# 4      a     1 FALSE
# 5      b     1 FALSE
# 6      b     1 FALSE
# 7      b     2  TRUE
# 8      b     1 FALSE
# 9      c     2 FALSE
# 10     c     3 FALSE
# 11     c     3  TRUE
# 12     c     2 FALSE
f我会:

is.first.max <- function(x) seq_along(x) == which.max(x)
is.last.max  <- function(x) rev(is.first.max(rev(x)))
transform(dat, RESULT = as.logical(ave(value, group, FUN = is.last.max)))
is.first.max
is.first.max <- function(x) seq_along(x) == which.max(x)
is.last.max  <- function(x) rev(is.first.max(rev(x)))
transform(dat, RESULT = as.logical(ave(value, group, FUN = is.last.max)))