[R] how do i vectorize relational queries in R

jim holtman jholtman at gmail.com
Thu Aug 20 00:35:24 CEST 2009


Is this what you want:

> data$Stratum <- meta$Stratum[data$Sample]
> data
  Sample Score Stratum
1      1     2    Tree
2      1     2    Tree
3      1     2    Tree
4      2     2    Tree
5      2     2    Tree
6      2     2    Tree
7      3     2   Shrub
8      3     2   Shrub
9      3     2   Shrub
>


On Wed, Aug 19, 2009 at 6:21 PM, chipmaney<chipmaney at hotmail.com> wrote:
>
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list