如何转换/重新采样/插值数据以在R中具有多个分组变量的整洁数据集中标准化变量长度?

时间:2018-05-23 13:56:26

标签: r dplyr tidyr

我的目标是规范化矢量的长度,以便在整洁的数据集中进行平均。使用约似乎是要走的路,但我不能让它在整齐的过程中有效地工作。一个问题可能与数据框中的大小调整有关。这是一个可重复的例子:

# create reproducible dataset
i = 80
I = 110
id = rep("AA", I+i)
event = rep("event1", I+i)
sub_event = NA
sub_event[1:i] = 1
sub_event[i+1:I] = 2
sub_event = as.factor(sub_event)
y1 = sin(seq(0, 5*pi, length.out = i))
y2 = sin(seq(0, 5*pi, length.out = I))
y3 = cos(seq(0, 5*pi, length.out = i))
y4 = cos(seq(0, 5*pi, length.out = I))
var1 = c(y1,y2)
var2 = c(y3,y4)

df1 <- data.frame(id, event, sub_event,var1, var2)
df2 <- df1
df2$event = "event2"
df <- rbind(df1, df2)
temp <- df
temp$id = "BB"
df <- rbind(df, temp)


# create a "time" vector for sub_event

df <- df %>% 
  group_by(id, event, sub_event) %>%
  mutate(sub_event_time = seq_along(var1)) %>%
  select(id, event, sub_event, sub_event_time, everything()) %>%
  ungroup()

绘制var1

# plot 
ggplot(df,
       aes(x=sub_event_time, y=var1, colour = sub_event)) + 
  geom_point() +
  geom_path() +
  facet_wrap(id~event)

enter image description here

我希望转换/重采样数据为每个sub_events获取var1的长度,使其成为每个id中每个事件中最长的sub_event的长度。

例如我们想要:事件1子事件的var1的长度1 =事件1子事件2的var1的长度(这是最长的)。

这是一次尝试:

# attempt for var1 only
aim.df <- df %>%
  ungroup() %>%
  select(-var2) %>%
  group_by(id, event) %>%
  mutate(max_sub_event_time = max(sub_event_time)) %>%
  mutate(var1 = approx(var1, n = max_sub_event_time)$y) 

这会返回以下错误:

    Error in mutate_impl(.data, dots) : 
    Column `var1` must be length 190 (the group size) or one, not 110
    In addition: Warning messages:
    1: In if (n <= 0) stop("'approx' requires n >= 1") :
    the condition has length > 1 and only the first element will be used
    2: In seq.int(x[1L], x[nx], length.out = n) :
    first element used of 'length.out' argument

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

步骤......

  1. group_by(id, event, sub_event)
  2. 删除sub_event_time,因为添加观察后它将无关紧要
  3. summarise approx函数的结果作为列表列(您必须将var1max_sub_event_time转换为approx的适当输入<) / LI>
  4. unnest生成的列表列
  5. 再次
  6. group_by(id, event, sub_event)并添加新的sub_event_time
  7. ...代码

    library(dplyr)
    library(tidyr)
    
    df %>%
      ungroup() %>%
      select(-var2) %>%
      group_by(id, event) %>%
      mutate(max_sub_event_time = max(sub_event_time)) %>% 
      group_by(id, event, sub_event) %>% 
      select(-sub_event_time) %>% 
      summarise(var1_int = list(approx(as.numeric(var1), n = first(max_sub_event_time))$y)) %>% 
      unnest() %>% 
      group_by(id, event, sub_event) %>% 
      mutate(sub_event_time = row_number())