0

This is the current data frame structure

value.           blue         red
1                   -1.22049503   -0.62733486
2                    1.61641224   0.43102051
3                    0.09079087   0.61619844
4                    0.32325956   -0.17718356 

want to change it to

value.               number       color
1                   -1.22049503   blue
1                   -0.62733486    red
2                    1.61641224   blue
2                    0.43102051    red
3                    0.09079087   blue
3                    0.61619844    red
4                    0.32325956   blue
4                   -0.17718356    red

I saw this question which does the other way. Transform structure of data frame in R

2 Answers2

0

tidyr::gather will do it. Assuming the data frame is named df1:

library(tidyr)
df1 %>% 
  gather(color, number, -value.)

If you want the result ordered by value. as in your example, add dplyr::arrange:

library(tidyr)
library(dplyr)
df1 %>% 
  gather(color, number, -value.) %>%
  arrange(value.)
neilfws
  • 32,751
  • 5
  • 50
  • 63
-1

@d.b's comment and @neilfws' answer are great. Here is another way:

library(dplyr)

df <- data.frame(
  value = c(1, 2, 3),
  blue = c(10, 30, 50),
  red = c(20, 40, 60)
)

df2 <- data.frame(
  value = rep(1:nrow(df), each = 2),
  color = rep(c("blue", "red"), nrow(df))
) %>%
  mutate(number = if_else(color == "blue", df$blue[value], df$red[value]))
OzanStats
  • 2,756
  • 1
  • 13
  • 26