ehrt1974
ehrt1974

Reputation: 1186

R data frame transformation values as names

I'd like to do the following data transformation in R

Name Value
type1 value1.1
type2 value2.1
type3 value3.1
type1 value1.2
type2 value2.2
type3 value3.2
type1 value1.3
type2 value2.3
type3 value3.3

should become:

       Name Value1 Value2 Value3
type1 value1.1 value1.2 value1.3
type2 value2.1 value2.2 value2.3
type3 value3.1 value3.2 value3.3

I've been looking into the cast command, but I can't see a way to do this :(

If anybody could help, I'd be very grateful :)

Upvotes: 0

Views: 83

Answers (3)

David Arenburg
David Arenburg

Reputation: 92310

Could try something like (if df is your data set)

df$Value2 <- paste0("Value", gsub("^.*\\.", "", df$Value)) # Creating an index column
library(reshape2)
dcast(df, Name ~ Value2, value.var = "Value")
#    Name   Value1   Value2   Value3
# 1 type1 value1.1 value1.2 value1.3
# 2 type2 value2.1 value2.2 value2.3
# 3 type3 value3.1 value3.2 value3.3

Upvotes: 4

ehrt1974
ehrt1974

Reputation: 1186

I've just found a good site that explains the cast function in more detail: An Introduction to reshape2

Using this, I've done the following:

mydata$Number <- rep("Value1", "Value2", "Value3", each=3)
dcast(mydata, Name~Number, value.var="Value")

This seems to work for me :)

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

The problem is that you are lacking a unique "Id" variable.

You can use getanID from my "splitstackshape" package for that, and then dcast.data.table to do the reshaping:

library(splitstackshape)
dcast.data.table(getanID(mydf, "Name"), Name ~ .id, value.var = "Value")
#     Name        1        2        3
# 1: type1 value1.1 value1.2 value1.3
# 2: type2 value2.1 value2.2 value2.3
# 3: type3 value3.1 value3.2 value3.3

Upvotes: 2

Related Questions