根据条件获取值之前的行数

时间:2017-01-10 23:43:39

标签: r

我的第一个data.frame结构如下:

structure(list(Trial = c("Left - 180 degrees", "Left - 300 degrees", 
"Left - 60 degrees", "Right - 180 degrees", "Right - 300 degrees", 
"Right - 60 degrees", "Left - 180 degrees", "Left - 300 degrees", 
"Left - 60 degrees", "Right - 180 degrees", "Right - 300 degrees", 
"Right - 60 degrees"), Region = c("Hamstring", "Hamstring", 
"Hamstring", "Hamstring", "Hamstring", "Hamstring", "Quad", "Quad", 
"Quad", "Quad", "Quad", "Quad"), PeakPower = c(118, 90, 
156, 105, 90, 140, 146, 111, 247, 186, 
133, 270)), .Names = c("Trial", "Region", "PeakPower"
), row.names = c(NA, -12L), class = "data.frame")

我希望根据PeakPowerTrial在下面的另一个数据框Region中找到每个RawData值。我还想计算达到PeakPower的时间(每行= 1秒)。这只是0和每个PeakPower值之间的行数。例如:

PeakPower <- c(0,0,0,0,3,5,8,19,20,0,0,0,0,0,60,65,88,90,94,99,100,105,107,118,114,100)
Trial <- c("Left - 180 degrees")
Region <- c("Hamstring")
RawData <- data.frame(cbind(PeakPower, Trial, Region))

左手 - {180}试验和腿筋区域达到PeakPower的时间为10行或10秒。

如何在R中完成此操作?

谢谢。

1 个答案:

答案 0 :(得分:1)

使用包dplyr

data_frame(PeakPower, Trial, Region) %>% 
  group_by(Trial,Region) %>% 
  mutate(Max=which.max(PeakPower)) %>% 
  filter(row_number()<=Max) %>%
  arrange(desc(row_number()))%>%
  mutate(Min=which.min(PeakPower)) %>% 
  filter(row_number()<Min) %>%
  summarise(PeakPower=max(PeakPower), Time=n()) %>%
  ungroup

# A tibble: 1 × 4
               Trial    Region PeakPower  Time
               <chr>     <chr>     <dbl> <int>
1 Left - 180 degrees Hamstring       118    10