[R] Odp: loop for inserting rows in a matrix

Petr PIKAL
Fri, 13 Aug 2010 09:25:05 -0000

Hi

First of all, use data frame instead of matrix. Matrix is vector with
dimensions and hence it can not have mixed values  (numeric, character,
date..).

So let's ASDF is your whole data frame

ASDF<-data.frame(Date=c("13/06/2006","19/06/2006","19/06/2006","19/06/2006","19/06/2006","19/06/2006","26/06/2006"),Trans=c(4,7,7,7,8,8,3),
Segm=c(2,5,5,4,4,5,2), some.data=rnorm(7))

Make whole desired output structure

whole<-expand.grid(Trans=1:9, Segm=1:8, Date=levels(DF$Date))

merged<-merge(whole, ASDF, all.x=TRUE)

Merge your data frame to required structure. Feel free to order it
according to your desire.

Regards
Petr



r-help-bounces at r-project.org napsal dne 13.08.2010 08:37:38:

> Dear R friends,
>
> I have a matrix with 2060 rows and 41 columns. One column is Date,
another is
> Transect, and another is Segment. I want to ensure that there are 9
Transects
> (1 to 9) for each Date, and 8 Segments (1 to 8) for each Transect in the

> matrix, by inserting rows where these are missing.
>
> I am new to coding, but am trying to write a loop which checks if each
of the
> transects already exists, and then adds a row in the appropriate place
if it
> doesn't (I have not tackled the segment part, since I am having
problems
with
> the Transect part). I have simplified the matrix to show the code I so
far
> have. The code seems to do the right thing for the first date, but not
on
> subsequent dates. The code is:
>
>
AerialSurveysm<-matrix(c("13/06/2006","19/06/2006","19/06/2006","19/06/
>
2006","19/06/2006","19/06/2006","26/06/2006",4,7,7,7,8,8,3,
2,5,5,4,4,5,2),
> nrow = 7, ncol = 3)
> colnames(AerialSurveysm) <-
c("Date","Transect","Segment")
>
> i=1   #start iteration for all dates
> k=2   #start iteration for all transects
> m<-unique(AerialSurveysm[,1])
>
> for (i in 1:length(m)) {      #for each date
>     for (k in 1:9) {         #do the following for the total number of
> transects that there are (1 to 9)
>      NewDat <-subset(AerialSurveysm, AerialSurveysm[,1]== m[i]) #select
> date to work on beginning with 1st
>      indx<-which(AerialSurveysm[,1]==m[i])
>      indx<-indx[[1]]
>      Check<-which(NewDat[,2]==k)
>      NewRow<-c(c(m[i]),k,0)
>       if(is.empty(Check)==TRUE)#if the selected date does not have a
transect
> equal to transect k
>         AerialSurveysm<-insertRow(AerialSurveysm,indx,NewRow) #add a row
to
> AerialSurveys.m in the location of the correct date
>      }
>   i=i+1
> }
>
> Thanks for any hints or thoughts on this (maybe I'm tackling it
completely the
> wrong way!)!
>
> Chandra
>
>
>
>
>    [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.