0

I have a table that looks like this:

id  pop  fre
A:1 sh   0.6
A:1 mi   0.2
A:2 sh   0.9
A:3 mi   0.5

What I want is creating a new table with the second column (pop) as a column names and values of (id) column without repetition. The corresponding values of (fre) column is to be used for filling the table. As an example the above table might looks like this:

id    sh    mi
A:1   0.6  0.2
A:2   0.9  NA
A:3   NA   0.5

I tried to use reshape function in R, however I keep getting an error about data-frame columns. I appreciate any ideas that might help.

Chris Watson
  • 1,347
  • 1
  • 9
  • 24
Waleed Omer
  • 103
  • 1
  • 7

1 Answers1

2

You can try dcast

library(reshape2)
dcast(df1, id~pop, value.var='fre')

Or

library(tidyr)
spread(df1, pop, fre)

Or using base R (based on the example showed)

 xtabs(fre~id+pop, df1)

Or with reshape from base R

 reshape(df1, idvar='id', timevar='pop', direction='wide')

data

df1 <- structure(list(id = c("A:1", "A:1", "A:2", "A:3"), pop = c("sh", 
"mi", "sh", "mi"), fre = c(0.6, 0.2, 0.9, 0.5)), .Names = c("id", 
"pop", "fre"), class = "data.frame", row.names = c(NA, -4L))

df1$pop <- factor(df1$pop, levels=unique(df1$pop))
akrun
  • 874,273
  • 37
  • 540
  • 662