[R] Searching for values

barb mainzel89 at hotmail.com
Thu May 3 13:28:06 CEST 2012


Hey YaoPau,

what you need are basically three things. If, for and matrix-operations. 

So a quick overview, how you could do it. (With focus on the idea, not 
how the columns and rows are arranged. 


# 1) Building the Vectors with c()

column1<-c("p103","p186","p145","p187","p197")
column2<-c("p666","p77","p198","p674","p302")

# 1) Building the vector with numbers and letters 
# you can use paste here (cat is also a useful function
# for similar purposes). Seq is obv a sequence. 
# Sep="" tells R to not split the letter and numbers
# try sep=" " for the difference

longvector<-(paste("p",seq(1:700),sep=""))

## rep can be used to create an empty vetor, not very
## elegant though

emptyvector<-rep(0,length(longvector))

## cbind for creating a matrix out of two vetors
matrix<-cbind(longvector,emptyvector)


#### Now the interesting part. More difficult to explain
## Focus on the middle term. If term of column 1 equals
## term in the matrix function you want to insert 1.
### Same thing for "a-1" below.
### no you want to perform this for all 700 rows = [length(longvector)]
### and for all values in column1 = [length(column1)]
## you will use "for" here. 


for (i in 1:length(longvector)){
  for (j in 1: length(column1)){
    if (column1[j]==matrix[,1][i]){
      matrix[,2][i]="1"
    }  
    if (column2[j]==matrix[,1][i]){
      matrix[,2][i]="a-1"
    }
  }  
}

--
View this message in context: http://r.789695.n4.nabble.com/Searching-for-values-tp4605213p4605722.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list