rileycattus
rileycattus

Reputation: 31

Converting dataframe levels into columns in R

Suppose I have a dataframe with 3 columns, as follows:

Sample  Compound     Area
1   A     Deet       22196836.0
2   A     Allethrin  NA
3   B     Deet       12890878.4
4   B     Allethrin  133063.1
  etc

The Sample column has 12 levels, Compound has 324 levels and the entire dataframe has 3888 total observations. How would I go about converting the "Sample" levels to individual columns, the "Compound" levels into rows and the corresponding "Area" filled in accordingly, as follows:

                 A            B           C            D
1   Deet         22196836.0   12890878.4
2   Allethrin    NA           133063.1

I know very little about R and apologize if this is basic stuff. I tried searching but don't think I'm using the correct lingo here to net me any useful results.

Upvotes: 1

Views: 80

Answers (3)

Michael Lawrence
Michael Lawrence

Reputation: 1021

Or just with the stats package, included with R:

reshape(df, timevar="Sample", idvar="Compound", direction="wide")

##    Compound   Area.A     Area.B
## 1      Deet 22196836 12890878.4
## 2 Allethrin       NA   133063.1

Upvotes: 1

jeremycg
jeremycg

Reputation: 24945

Your data is in "long format", and you want it in "wide format". See here for a quick explanation.

There are a range of ways to reshape data between these modes in R. tidyr is a package written exclusively for doing this:

library(tidyr)
spread(dta, Sample, Area)
   Compound        A          B
1 Allethrin       NA   133063.1
2      Deet 22196836 12890878.4

Upvotes: 2

agstudy
agstudy

Reputation: 121568

Using reshape2 package you can reshape it in the wide format:

dcast(Compound~Sample,data=dat)

##    Compound        A          B
## 1 Allethrin       NA   133063.1
## 2      Deet 22196836 12890878.4

Upvotes: 2

Related Questions