2

I got some data like this

structure(list(id = c(1, 1, 1), time1 = c(10, 20, 30), time2 = c(15, 25, 35)), row.names = c(NA, 3L), class = "data.frame")

and I want to create a single column from the two columns in the above data

structure(list(id = c(1, 1, 1, 1, 1, 1), time = c(10, 15, 20, 25, 30, 35)), row.names = c(NA, 6L), class = "data.frame")

I dont think its the same as converting into long format because I dont want two columns as a result of gather(), with one the names of the columns used and one the values.

r2evans
  • 141,215
  • 6
  • 77
  • 149
kam
  • 345
  • 1
  • 8
  • 1
    We could use add_row from tibble package. This answer is not in the duplicate question. So where should I post my answer? – TarJae May 10 '21 at 05:14

2 Answers2

1

We can use pivot_longer and this should be more general as it can also do reshaping based on other patterns and multiple columns as well. Note that pivot_longer succeeds the reshape2 function melt with more enhanced capabilities and bug fixes

library(dplyr)
library(tidyr)
pivot_longer(df1, cols = time1:time2, values_to = 'time') %>%
      select(-name)

-output

# A tibble: 6 x 2
#     id  time
#  <dbl> <dbl>
#1     1    10
#2     1    15
#3     1    20
#4     1    25
#5     1    30
#6     1    35

Or using base R with stack

transform(stack(df1[-1])[1], id = rep(df1$id, 2))[2:1]

Or can use data.frame with unlist

data.frame(id = df1$id, value = unlist(df1[-1], use.names = FALSE))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Alternative to tidyr, though that's a good way to do it:

reshape2::melt(dat, "id")[,-2]
#   id value
# 1  1    10
# 2  1    20
# 3  1    30
# 4  1    15
# 5  1    25
# 6  1    35

(Normally it includes the pivoted column names as a column itself, so the [,-2] removes that since your expected output didn't have it. You can do just melt(.) if you want/need to keep it.)

r2evans
  • 141,215
  • 6
  • 77
  • 149