dplyr中的OR语句以计算因变量

时间:2018-10-01 10:20:55

标签: r dplyr

我想根据列的规格计算一个变量。

example.df <- 
data.frame(trial.number = rep(1:10, 
each = 10), GY = sample(-200:200, 
100, replace = T), target.position 
= rep(c("up","down","up","down", 
"up"), each = 20))

test <- example.df %>% 
  group_by(trial.number) %>% 
  summarise(pxpos = 
max(GY[target.position == "up"]) | 
min(GY[target.position == "down"]))

因此,如果target.position为“ up”,则我想知道该次试验中的最大GY,当target.position =“ down”时,我希望变量取min(GY)。

但是这不起作用。我确实相信有可能!感谢您的帮助

3 个答案:

答案 0 :(得分:3)

假设每个target.positiontrial.numer的值始终相同,我们可以group_by trial.number并计算max(GY)(如果第一个值为“向上”,否则计算min

library(dplyr)

example.df %>%
    group_by(trial.number) %>%
    summarise(pxpos = if_else(target.position[1] == "up", max(GY), min(GY)))



#   trial.number pxpos
#          <int> <dbl>
# 1            1   177
# 2            2   183
# 3            3  -142
# 4            4  -191
# 5            5   143
# 6            6   158
# 7            7  -162
# 8            8  -200
# 9            9   194
#10           10   113

@Axeman指出,if_else很慢,我们可以改用简单的if else

example.df %>%
   group_by(trial.number) %>%
   summarise(pxpos = if (target.position[1] == "up")  max(GY) else min(GY))

数据

set.seed(123)
example.df <- data.frame(trial.number = rep(1:10, each = 10), 
             GY = sample(-200:200,100, replace = T), 
             target.position = rep(c("up","down","up","down", 
                 "up"), each = 20))

答案 1 :(得分:1)

另一种ActionDescriptorFilterProvider解决方案,使用@Ronak Shah提供的数据:

HttpConfiguration

答案 2 :(得分:1)

我们可以使用case_when

example.df %>%
  group_by(trial.number) %>%
  summarise(pxpos = case_when(first(target.position) == "up" ~ max(GY), 
                   TRUE ~ min(GY)))
# A tibble: 10 x 2
#   trial.number pxpos
#            <int> <dbl>
#1            1   177
#2            2   183
#3            3  -142
#4            4  -191
#5            5   143
#6            6   158
#7            7  -162
#8            8  -200
#9            9   194
#10          10   113