Alex
Alex

Reputation: 667

R: how to convert a data frame

I have a table like this:

    C1, C2, C3
1   1.1, 2.3, 5.5
2   3.3, 4.3, 2.5

I want to get it into the format of:

Type Time
 1   1.1
 1   2.3
 1   5.5
 2   3.3
 2   4.3
 2   2.5

I have tried:

 pivot_longer(cols = C1:C3, names_to = "Type", values_to = "Time")

However, I get the first set followed by the second.

Sample reproducible data:

df <- tribble(
  ~ C1, ~ C2, ~ C3,
   1.1, 2.3, 5.5,
   3.3, 4.3, 2.5
)

Upvotes: 1

Views: 46

Answers (2)

Anoushiravan R
Anoushiravan R

Reputation: 21908

You can use the following code. For your solution to work you only need to add a row id before pivoting:

library(dplyr)
library(tidyr)

df %>%
  mutate(Type = row_number()) %>%
  pivot_longer(-Type, names_to = "name", values_to = "Time") %>%
  select(-name)

# A tibble: 6 x 2
   Type  Time
  <int> <dbl>
1     1   1.1
2     1   2.3
3     1   5.5
4     2   3.3
5     2   4.3
6     2   2.5

Upvotes: 1

Sirius
Sirius

Reputation: 5429


your.matrix <- rbind(
  c(1.1, 2.3, 5.5),
  c(3.3, 4.3, 2.5)
)
rownames(your.matrix) <- c("1","2")

your.matrix <- as.matrix( your.matrix ) # if you started with a data.frame

long.data <- data.frame(
    Type = rep( rownames(your.matrix), each=ncol(your.matrix) )
    Time = as.numeric(t(your.matrix))
)

Data being this simple, just turning it into a vector (with as.numeric), and handling the rownames-to-column operation by hand might be just as simple as pivoting.

To do it the chained dplyr way, rownames_to_column from tibble might come in handy:


pivot_longer( 
    rownames_to_column( your.matrix, "Type" ), 
    cols=matches("^C\\d")
) %>% select(-name)

Output:

  Type  value
  <chr> <dbl>
1 1       1.1
2 1       2.3
3 1       5.5
4 2       3.3
5 2       4.3
6 2       2.5

Upvotes: 1

Related Questions