Hello,
I have a matrix for example
B <- as.matrix(read.table(text="
77 15 70 44
90 61 36 63
51 10 90 99"))
I have an object called M
, which contain 57, 60, 75
I want to compare 57 to each number in the first row, to see if greater equal to or less then them.
Then 60 to each number in the second row , to see if greater equal to or less then them. And keep going like that.
If greater output 1 and less then output 0.
I have tried but everything is way off, like cal <- lapply(B, 1, function(x) x<- M <= B)
Could anyone direct me to information on this or offer suggestion on how might be done.
Thanks
Thanks very much. Just Quick question, what does
Mean /do ?
I can follow the rest.
It's first good to note what
cbind(A,B)
is doing.B
is a matrix and thecbind()
command is just making a new matrix ofA
andB
withA
as the first column. Why might someone want to do this? Because then you can useapply()
and you automatically have all the information available in the function being applied. Were one not to do this, then either you'd have to usemapply()
and split things yourself or completely restructure things such that you apply over a vector of row indices and then subsetA
andB
inside the applied function (odds are good that this is slower). I should note that all of this is only needed because R has TERRIBLE loop performance. In any other language you'd justfor(i=0; i<nrow(B);i++) {...}
, which is probably more intuitive if you know any other languages.So then what is the
x
thatfunction(x)
is receiving? For the first iteration, it'll bec(57,77,15,70,44)
, thenc(60,90,61,36,63)
and finallyc(75,51,10,90,99)
. In other words, the threshold value that you want to compare things against isx[1]
. SoA=x[1]
just saves that value to a variable andx=x[-1]
then removes it fromx
, since we don't want to compare the number to itself. I should note that this isn't absolutely required, but either you do it in the function or afterwards.The
t()
function transposes a matrix. If you don't know what that means, then just run that step with/without thet()
function and compare the results (it'll be immediately obvious to you what transposing a matrix means). This is only needed because of how the apply function works. Sincefunction(x)
always returns a vector of the same length (n
), the output ofapply()
is a matrix withn
rows and columns equal to the number of rows in the input (i.e., it's transposed). This kind of output can sometimes be very useful, but probably not in your case, so I transposed the output.