[R] how do i vectorize relational queries in R

Don MacQueen macq at llnl.gov
Thu Aug 20 01:42:54 CEST 2009


Does
   merge(data,meta)
give what you want?

FWIW:

  "append" to a dataframe would normally mean to add more rows (or at 
least that's how I use it), but you appear to be adding a column.

"data" is the name of an R function, best avoided for other uses.

You're assigning the column names the hard way. Try
   mydata <- data.frame(Sample=c(1,1,1,2,2,2,3,3,3), Score=rep(2,9))

To avoid the factors, use
   meta <- data.frame(Score=c(1,2,3), Stratum = I(c("Tree","Tree","Shrub")) )
## that's an upper case letter "i" in I()
or
   meta <- data.frame(Score=c(1,2,3), Stratum = 
c("Tree","Tree","Shrub"), stringsAsFactors=FALSE )
## easily found in the help page for data.frame

-Don

At 3:21 PM -0700 8/19/09, chipmaney 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.


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062




More information about the R-help mailing list