[R] how do i vectorize relational queries in R

chipmaney chipmaney at hotmail.com
Thu Aug 20 00:21:18 CEST 2009


I am basically trying to append a value(vector) to one dataframe using a
relational value from another dataframe.  Obviously, I can use a loop to
accomplish this.  However, is there a way to vectorize it?

Example:

> data <- data.frame(c(1,1,1,2,2,2,3,3,3),rep(2,9)); names(data) <-
> c("Sample","Score")
> meta <- data.frame(c(1,2,3),c("Tree","Tree","Shrub")); names(meta) <-
> c("Sample","Stratum")


The following attempt at vectorizaton doesn't work:

> data$Stratum <- meta$Stratum[which(data$Sample == meta$Sample)]

> data$Stratum
[1] Tree <NA> <NA> Tree <NA> <NA> Tree <NA> <NA>

And actually, when I try to run a loop, the operation converts the string to
a factor.  

> for (i in 1:length(data[,1])) data$Stratum[i] <-
> meta$Stratum[which(meta$Sample == data$Sample[i])]

>data
  Sample Score Stratum
1      1     2       2
2      1     2       2
3      1     2       2
4      2     2       2
5      2     2       2
6      2     2       2
7      3     2       1
8      3     2       1
9      3     2       1

Argghhhh....I don't want a factor, and anyway I don't want to use a loop...

Can anyone help with these two issues???
-- 
View this message in context: http://www.nabble.com/how-do-i-vectorize-relational-queries-in-R-tp25052929p25052929.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list