Reshape data from long to wide, with time in new wide variable name

后端 未结 4 943
时光说笑
时光说笑 2020-12-15 02:04

I have a data frame that I would like to merge from long to wide format, but I would like to have the time embedded into the variable name in the wide format. Here is an ex

4条回答
  •  一生所求
    2020-12-15 02:29

    I gave up on the old reshape() command 2 years ago (not Hadley's). It seems figuring that damn thing out each time was actually harder than just doing it the 'hard' way, which is much more flexible.

    Your data in your example are all nicely sorted. You might have to sort your real data by var name and time first.

    (renamed your tmpdata to tmp, made value numeric)

    y <- lapply(split(tmp, tmp$id), function(x) x$value)
    df <- data.frame(unique(tmp$id,), do.call(rbind,y))
    names(df) <- c('id', as.character(tmp$time:tmp$var))
    

提交回复
热议问题