Reputation: 31
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
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
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
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