R dplyr - 根据另一列中特定值的位置从一列中选择值

时间:2017-12-06 14:52:45

标签: r dplyr

我正在处理步态周期数据。我为每个id和步态试验标记了8个事件。每次试验中“LFCH”和“RFCH”值出现两次,因为它们代表左右腿步态周期的开始和结束。

示例数据框:

df <- data.frame(ID = rep(1:5, each = 16),
                 Gait_nr = rep(1:2, each = 8, times=5),
                 Frame = rep(c(1,5,7,9,10,15,22,25), times = 10),
                 Marks = rep(c("LFCH", "LHL", "RFCH", "LTO", "RHL", "LFCH", "RTO", "RFCH"), times =10) 

head(df,8)
  ID Gait_nr Frame Marks
1  1       1     1  LFCH
2  1       1     5   LHL
3  1       1     7  RFCH
4  1       1     9   LTO
5  1       1    10   RHL
6  1       1    15  LFCH
7  1       1    22   RTO
8  1       1    25  RFCH

我喜欢创造类似

的东西
Total_gait_left = Frame[The last time Marks == "LFCH"] - Frame[The first time Marks == "LFCH"]

我当前的代码解决了问题,但取决于Frame值的位置而不是Marks中的实际值。任何不遵循正常步态模式的人都会得到错误的代码值。

library(tidyverse)
l <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("L.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "left")

r <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("R.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "right")

val <- union(l,r, by=c("ID", "Gait_nr", "Side")) %>% arrange(ID, Gait_nr, Side)

你可以帮我改变一下,让我的代码更稳定吗?帧[4]到Frame [Marks ==“LFCH”最后一次]?

2 个答案:

答案 0 :(得分:2)

如果LFCHRFCH同时发生两次,您可以过滤,然后在diff中使用summarize

df %>% 
    group_by(ID, Gait_nr) %>% 
    summarise(
        left = diff(Frame[Marks == 'LFCH']), 
        right = diff(Frame[Marks == 'RFCH'])
    )

# A tibble: 10 x 4
# Groups:   ID [?]
#      ID Gait_nr  left right
#   <int>   <int> <dbl> <dbl>
# 1     1       1    14    18
# 2     1       2    14    18
# 3     2       1    14    18
# 4     2       2    14    18
# 5     3       1    14    18
# 6     3       2    14    18
# 7     4       1    14    18
# 8     4       2    14    18
# 9     5       1    14    18
#10     5       2    14    18

答案 1 :(得分:1)

我们可以使用first包中的lastdplyr

library(dplyr)

df2 <- df %>%
  filter(Marks %in% "LFCH") %>%
  group_by(ID, Gait_nr) %>%
  summarise(Total_gait = last(Frame) - first(Frame)) %>%
  ungroup()
df2
# # A tibble: 10 x 3
#       ID Gait_nr Total_gait
#    <int>   <int>      <dbl>
#  1     1       1         14
#  2     1       2         14
#  3     2       1         14
#  4     2       2         14
#  5     3       1         14
#  6     3       2         14
#  7     4       1         14
#  8     4       2         14
#  9     5       1         14
# 10     5       2         14