-1

I've got an R data frame in the form of

my.data1 = data.frame(sex = c("m", "f"),
                     A = c(1, 2),
                     B = c(3, 4))

However, I'd like my data to be in the form of

my.data2 = data.frame(value = c(1, 2, 3, 4),
                     group = c("A", "A", "B", "B"),
                     sex = c("m", "f", "m", "f"))

So basically, I wanna turn some former columns ("A" and "B") into table cells under the new column "group" and simultaneously collect all former table cells under one new column "value".

What is the easiest way to convert the data accordingly?

Thanks in advance!

1 Answers1

0

A close result to what you want is reached using reshape2 and melt() function. You can define a variable as id and the data is reshaped:

library(reshape2)
#Data
my.data1 = data.frame(sex = c("m", "f"),
                      A = c(1, 2),
                      B = c(3, 4))
#Reshape
my.data2 <- melt(my.data1,id.vars = 'sex')

Output:

  sex variable value
1   m        A     1
2   f        A     2
3   m        B     3
4   f        B     4

If you wanna go further, you can use a tidyverse approach with pivot_longer(). In this function you also have to set a reference column as id with cols argument:

library(tidyverse)

my.data1 %>% pivot_longer(cols = -sex)

Output:

# A tibble: 4 x 3
  sex   name  value
  <fct> <chr> <dbl>
1 m     A         1
2 m     B         3
3 f     A         2
4 f     B         4
Duck
  • 39,058
  • 13
  • 42
  • 84