0

I have a data frame that i want to transpose (i suppose transpose is the correct word). The code below will give a simplified Data frame.

tests <- c("TestA", "TestB", "TestC")
bg <- c(23, 13, 15)
s1 <- c(21,15,17)
s2 <- c(27,25,11)
s3 <- c(24,14,18)
df <- data.frame(tests,bg,s1,s2,s3)

I want to transpose/ reshape this to have the following structure:

enter image description here

Please keep in mind that there could be up to 20 tests, and 50 series (s1, s2....s50)

Pythonuser
  • 203
  • 1
  • 11

3 Answers3

1

Get the data in long form and change the variable for wide form :

library(tidyr)
df %>%
  pivot_longer(cols = -tests) %>%
  pivot_wider(names_from = tests, values_from = value)

#  name  TestA TestB TestC
#  <chr> <dbl> <dbl> <dbl>
#1 bg       23    13    15
#2 s1       21    15    17
#3 s2       27    25    11
#4 s3       24    14    18

Or with data.table dcast + melt

library(data.table)
dcast(melt(setDT(df), id.vars = 'tests'), variable~tests, value.var = 'value')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

standard data.table::transpose-procedure

data.table::transpose( df, make.names = "tests", keep.names = "name" )

#   name TestA TestB TestC
# 1   bg    23    13    15
# 2   s1    21    15    17
# 3   s2    27    25    11
# 4   s3    24    14    18
Wimpel
  • 26,031
  • 1
  • 20
  • 37
0

Base R one-liner:

setNames(data.frame(t(df)[2:ncol(df),]), t(df$tests))
hello_friend
  • 5,682
  • 1
  • 11
  • 15