1

UPDATED:

I have dataframes inside a list that looks like this:

v1 <- data.frame(time = c(1, 3, 5, 9, 33),
                 X = c(4, 3, 2, 3, 12),
                 SE = c(1, 2, 3, 2, 1))
v2 <- data.frame(time = c(1, 3, 5, 9, 33),
                    Y = c(12, 3, NA, 2, 4),
                 SE = c(1, 2, 1, 12, 3))
list <- list(v1, v2)

I want to melt/reduce it to look like this:

   time variable value SE
1     1        X     4  1
2     3        X     3  2
3     5        X     2  3
4     9        X     3  2
5    33        X    12  1
6     1        Y    12  1
7     3        Y     3  2
8     5        Y    NA  1
9     9        Y     2 12
10   33        Y     4  3

So far I've tried this code to no avail.

data <- list %>% reduce(full_join, by = "time") 
data2 <- melt(data, id = c("time"))

Thank you!

0

1 Answer 1

1

We can use melt with patterns

library(data.table)
melt(setDT(data), measure = patterns('X|Y', 'SE'), 
   value.name = c('value', 'SE'))[, variable := c("X", "Y")[variable]][]
#     time variable value SE
# 1:    1        X     4  1
# 2:    3        X     3  2
# 3:    5        X     2  3
# 4:    9        X     3  2
# 5:   33        X    12  1
# 6:    1        Y    12  1
# 7:    3        Y     3  2
# 8:    5        Y    NA  1
# 9:    9        Y     2 12
#10:   33        Y     4  3

Or using pivot_longer

library(tidyr)
library(stringr)
library(dplyr)
data %>%
    rename_at(vars(X, Y), ~ str_c('value.', tolower(.))) %>% 
    pivot_longer(cols = -time, names_to = c('.value', 'variable'), 
        names_sep="\\.", values_drop_na = TRUE) %>% 
    arrange(variable)
# A tibble: 10 x 4
#    time variable value    SE
#   <dbl> <chr>    <dbl> <dbl>
# 1     1 x            4     1
# 2     3 x            3     2
# 3     5 x            2     3
# 4     9 x            3     2
# 5    33 x           12     1
# 6     1 y           12     1
# 7     3 y            3     2
# 8     5 y           NA     1
# 9     9 y            2    12
#10    33 y            4     3
1
  • I've made a mistake in my post and have updated it. Could you take a look again? Thank you!
    – Drew
    Commented Jun 5, 2020 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.