3

给定这样的数据框:

  gid set  a  b
1   1   1  1  9
2   1   2 -2 -3
3   1   3  5  6
4   2   2 -4 -7
5   2   6  5 10
6   2   9  2  0

如何对gid具有最大值set和 1/0 的唯一数据框进行子集/分组,其a值是否大于其b值?

所以在这里,它会是,呃...

1,3,0
2,9,1

SQL中的一种愚蠢的简单事情,但我想更好地控制我的R,所以......

4

3 回答 3

6

小菜一碟dplyr

dat <- read.table(text="gid set  a  b
1   1  1  9
1   2 -2 -3
1   3  5  6
2   2 -4 -7
2   6  5 10
2   9  2  0", header=TRUE)

library(dplyr)

dat %>%
  group_by(gid) %>%
  filter(row_number() == which.max(set)) %>%
  mutate(greater=a>b) %>%
  select(gid, set, greater)

## Source: local data frame [2 x 3]
## Groups: gid
## 
##   gid set greater
## 1   1   3   FALSE
## 2   2   9    TRUE

如果您真的需要1's 和0's 并且这些dplyr 会引起任何焦虑:

dat %>%
  group_by(gid) %>%
  filter(row_number() == which.max(set)) %>%
  mutate(greater=ifelse(a>b, 1, 0)) %>%
  select(gid, set, greater) %>%
  ungroup

## Source: local data frame [2 x 3]
## 
##   gid set greater
## 1   1   3       0
## 2   2   9       1

你可以在没有管道的情况下做同样的事情:

ungroup(
  select(
    mutate(
      filter(row_number() == which.max(set)), 
      greater=ifelse(a>b, 1, 0)), gid, set, greater))

但是……但是……为什么?!:-)

于 2015-01-21T02:00:04.243 回答
3

这是一种data.table可能性,假设您的原始数据被称为df.

library(data.table)

setDT(df)[, .(set = max(set), b = as.integer(a > b)[set == max(set)]), gid]
#    gid set b
# 1:   1   3 0
# 2:   2   9 1

请注意,为了考虑多max(set)行,我将set == max(set)其用作子集,以便这将返回与最大值有关联的相同行数(如果这有任何意义的话)。

并由@thelatemail 提供,另一个数据表选项:

setDT(df)[, list(set = max(set), ab = (a > b)[which.max(set)] + 0), by = gid]
#    gid set ab
# 1:   1   3  0
# 2:   2   9  1
于 2015-01-21T02:27:37.340 回答
1

base R中,您可以使用ave

indx <- with(df, ave(set, gid, FUN=max)==set)
#in cases of ties
#indx <- with(df, !!ave(set, gid, FUN=function(x) 
#                  which.max(x) ==seq_along(x)))


transform(df[indx,], greater=(a>b)+0)[,c(1:2,5)]
#   gid set greater
# 3   1   3       0
# 6   2   9       1
于 2015-01-21T04:43:44.070 回答