[R] define variables from rows of a matrix

Eik Vettorazzi E.Vettorazzi at uke.uni-hamburg.de
Wed Aug 10 10:56:25 CEST 2011


Hi,
I was irritated about your printed last row of A, which apart from
definition contains a 20. Anyway, how about this:

y<-x<-rep(NA,nrow(A))

#its not clear, whether multiple values of 100 can occur in a single
#row, and what to do, when 100 is found before and after 20, so you may
#alter the indexing as you need:

ind<-subset(merge(which(A==20,arr.ind=T),which(A==100,arr.ind=T),by="row",all.x=T),col.x<col.y|is.na(col.y))

x[ind$row]<-ind$col.x
y[ind$row]<-ind$col.y
x
y

which places an NA in x and y for all "no shows". I did not get the
logic behind setting x[3] to ">5" but x[5] to NA (same for y[3], y[4]),
so this is left for you to implement.

cheers.


Am 10.08.2011 08:15, schrieb gallon li:
> I have a following matrix and wish to define a variable based the variable
> 
>  A=matrix(0,5,5)
> A[1,]=c(30,20,100,120,90)
> A[2,]=c(40,30,20,50,100)
> A[3,]=c(50,50,40,30,30)
> A[4,]=c(30,20,40,50,50)
> A[5,]=c(30,50,NA,NA,100)
>> A
>      [,1] [,2] [,3] [,4] [,5]
> [1,]   30   20  100  120   90
> [2,]   40   30   20   50  100
> [3,]   50   50   40   30   30
> [4,]   30   20   40   50   50
> [5,]   30   20   NA   NA  100
> I want to define two variables:
> 
> X is the first column in each row that is equal to 20, for example, for the
> first row, I need X=2; 2nd row, X=3; 3rd row, X>5; 3th row, X=2, 5th row,
> X=NA;
> 
> Y is then the first column in each row that is equal to 100 if before this a
> 20 has been reached, for example, for the first row, Y=3; 2nd row, Y=5; 3rd
> row, Y=NA, 4th row, Y>5; 5th row, Y=NA.
> 
> the matrix may involve NA as well.
> 
> How can I define these two variables quickly? (When X>5 or Y>5, we can
> arbitrarily assign a value 6, and this is different from being NA)
> 
> 	[[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.

-- 
Eik Vettorazzi

Department of Medical Biometry and Epidemiology
University Medical Center Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/7410-58243
F ++49/40/7410-57790



More information about the R-help mailing list