Reputation: 416
I would like to transpose a data frame using a name column to create new column names. Here is my input:
Name X Y Z
sample1_A 1 2 3
sample1_B 3 2 1
sample2_A 1 2 3
sample2_B 3 2 1
And expected output:
Name XA XB YA YB ZA ZB
sample1 1 3 2 2 3 1
sample2 1 3 2 2 3 1
I though I could you transpose function, but I am not sure how to deal with column and row names.
Thanks in advance!
Upvotes: 1
Views: 518
Reputation: 887531
We can use dcast
from data.table
which can take multiple value.var
columns
library(data.table)
dcast(setDT(df1)[, c("Name", "grp") := tstrsplit(Name, "_")],
Name ~grp, value.var = c("X", "Y", "Z"), sep = "")
# Name XA XB YA YB ZA ZB
#1: sample1 1 3 2 2 3 1
#2: sample2 1 3 2 2 3 1
Upvotes: 1