0

I am self-taught useR so please bear with me.

I have something similar the following dataset:

individual  value
a   0.917741317
a   0.689673689
a   0.846208486
b   0.439198006
b   0.366260159
b   0.689985484
c   0.703381117
c   0.29467743
c   0.252435687
d   0.298108973
d   0.42951805
d   0.011187204
e   0.078516181
e   0.498118235
e   0.003877632

I would like to create a matrix with the values for a in column1, values for b in column2, etc. [I also add a 1 at the bottom of every column for a later algebra operations]

I have tried so far:

  for (i in unique(df$individual)) {
    values <- subset(df$value, df$individual == i)
    m <- cbind(c(values[1:3],1))

  }

I get a (4,1) matrix with the last individual values. What is missing to make it additive for each loop and get all as many columns as individuals?

user3507584
  • 3,246
  • 5
  • 42
  • 66
  • 1
    `reshape2` is a better solution, but here is a dumb way `matrix(DF$value, nrow = 3)` – Vlo Aug 04 '14 at 13:57
  • 1
    That doesn't look dumb to me. Assign to res.mtx and use `rbind( res.mtx, rep(1, ncol(res.mtx) ) )` – IRTFM Aug 04 '14 at 18:42

1 Answers1

2

This operation is called "reshaping". There is a base function, but I find it easier with the reshape2 package:

DF <- read.table(text="individual  value
a   0.917741317
a   0.689673689
a   0.846208486
b   0.439198006
b   0.366260159
b   0.689985484
c   0.703381117
c   0.29467743
c   0.252435687
d   0.298108973
d   0.42951805
d   0.011187204
e   0.078516181
e   0.498118235
e   0.003877632", header=TRUE)

DF$id <- 1:3

library(reshape2)
DF2 <- dcast(DF, id ~ individual)
DF2[,-1]
#          a         b         c         d           e
#1 0.9177413 0.4391980 0.7033811 0.2981090 0.078516181
#2 0.6896737 0.3662602 0.2946774 0.4295180 0.498118235
#3 0.8462085 0.6899855 0.2524357 0.0111872 0.003877632
Roland
  • 127,288
  • 10
  • 191
  • 288
  • What I meant was, there seems to be lots of cruft / quirks / 20-year-old gotchas in R. `reshape2` makes programming in R a bit cleaner / easier; would you know of other small clean packages that help ? – denis Jun 24 '15 at 13:23
  • That depends strongly on what you want to do. I don't know many "cruft / quirks / 20-year-old gotchas" in R. – Roland Jun 24 '15 at 13:33
  • Well, [The R inferno](http://www.burns-stat.com/documents/books/the-r-inferno/) is "A book about trouble spots, oddities, traps, glitches in R." Thanks anyway. – denis Jun 25 '15 at 13:52