Reputation: 1
I have a data frame looking like this : data.frame name cond
CONDITION CONT1 CONT2 CONT3 CONT4
result 16.2 2.5 6.5 0.75
Test.ratio 0.23 0.15 2.5 3.5
What I want to do get is:
CONDITION Result test.ratio
CONT1 16.2 0.62
CONT2 2.5 0.15
CONT3 6.5 2.5
CONT4 0.75 3.5
I tried using the melt function but it didnt work.
Cond.long <- melt(cond, idvar = "condition"))
I'm new to R.
Upvotes: 0
Views: 76
Reputation: 102529
Here is a data.table
option using dcase
+ melt
> dcast(melt(setDT(df), id.vars = "CONDITION"), variable ~ CONDITION)
variable Test.ratio result
1: CONT1 0.23 16.20
2: CONT2 0.15 2.50
3: CONT3 2.50 6.50
4: CONT4 3.50 0.75
Upvotes: 0
Reputation: 8880
base
df <- read.table(text = "CONDITION CONT1 CONT2 CONT3 CONT4
result 16.2 2.5 6.5 0.75
Test.ratio 0.23 0.15 2.5 3.5 ", header = T)
new <- t(df[, -1])
colnames(new) <- df[, 1]
new
#> result Test.ratio
#> CONT1 16.20 0.23
#> CONT2 2.50 0.15
#> CONT3 6.50 2.50
#> CONT4 0.75 3.50
Created on 2021-03-12 by the reprex package (v1.0.0)
Upvotes: 1
Reputation: 11596
Does this work:
library(dplyr)
library(tidyr)
df %>% pivot_longer(cols = starts_with('CONT')) %>%
pivot_wider(names_from = CONDITION) %>% select('CONDITION' = name, 2,3)
# A tibble: 4 x 3
CONDITION result Test.ratio
<chr> <dbl> <dbl>
1 CONT1 16.2 0.23
2 CONT2 2.5 0.15
3 CONT3 6.5 2.5
4 CONT4 0.75 3.5
Upvotes: 0