canadianer
canadianer

Reputation: 133

R: data.frame to vector

Let me preface this question by saying that I know very little about R. I'm importing a text file into R using read.table("file.txt", T). The text file is in the general format:

header1    header2
a          1
a          4
b          3
b          2

Each a is an observation from a sample and similarly each b is an observation from a different sample. I want to calculate various statistics of the sets of a and b which I'm doing with tapply(header2, header1, mean). That works fine.

Now I need to do some qqnorm plots of a and b and draw with qqline. I can use tapply(header2, header1, qqnorm) to make quantile plots of each BUT using tapply(header2, header1, qqline) draws both best fit lines on the last quantile plot. Programatically that makes sense but it doesn't help me.

So my question is, how can convert the data frame to two vectors (one for all a and one for all b)? Does that make sense? Basically, in the above example, I'd want to end up with two vectors: a=(1,4) and b=(3,2).

Thanks!

Upvotes: 2

Views: 483

Answers (1)

mnel
mnel

Reputation: 115382

Create a function that does both. You won't be able (easily at least) to revert to an old graphics device.

e.g.

with(dd, tapply(header2,header1,  function(x) {qqnorm(x); qqline(x)}))

You could use data.table here for coding elegance (and speed)

You can pass the equivalent of a body of a function that is evaluated within the scope of the data.table e.g.

library(data.table)
DT <- data.table(dd)
DT[, {qqnorm(x)
      qqline(x)}, by=header1]

You don't really want to pollute your global environments with lots of objects (that will be inefficient).

Upvotes: 4

Related Questions