Cast multiple value.var columns simultaneiously for reshaping data from Long to Wide in R

While working with R, reshaping dataframe from wide format to long format is relatively easier than the opposite. Especially when you want to reshape a dataframe to a wide format with multiple columns for value.var in dcast. Let’s look at an example dataset:

1

From v1.9.6 of data.table, we can cast multiple value.var by this syntax:

testWide <- dcast(setDT(test), formula = time ~ country, value.var = c(‘feature1′,’feature2’))

All you need is add ‘setDT’ for the dataframe and pass the list of value.var to it.

2

Advertisements

One thought on “Cast multiple value.var columns simultaneiously for reshaping data from Long to Wide in R”

  1. I have looked and looked and looked and looked and then I found you!

    AND IT WORKED! What a delight.

    In the past I have worked with Dyadic data and I used Dave Kenny’s tool to reshape it from long to wide format whilst maintaining the column labels. But I couldn’t work out how to do it in R with groups of people.

    Thanks so much for this you have made a huge difference to my week.

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s