[R] Data reshaping with conditions

Jim Lemon drjimlemon at gmail.com
Fri Apr 22 00:28:43 CEST 2016


In R, square brackets [] are called "extraction operators" as they are
interpreted so as to "extract" the parts of an object specified by the
information within them. Your message contained only part of the line
below:

AltB<-svdatstr[row,indicesA][svdatstr[row,indicesA]<svdatstr[row,"maxB"]]

Extraction operators may be specified sequentially or nested. Both are
used in this line. However, to understand how it works, first look at
the line that defines the value of "indicesA":

 indicesA<-count_ind[as.logical(match(svdatstr[row,type_ind],"A",0))]

This defines a vector of logical (TRUE/FALSE) values for the valid
"Count" values in the current row by finding the matches in the "type"
values for the character string "A". The reason I have used the
"match" function instead of "=="" is to get rid of the NA values that
would have been generated by specifying "0" (zero) in the
"incomparables" argument. I then used the "as.logical" function to
transform the "1" AND "0" to TRUE and FALSE..This logical vector can
then be placed within square brackets to "extract" the valid "Count"
values that have a "type" of "A" in the current row of svdatstr.

Having done this, the expression within the latter pair of extraction
operators can be translated as "Return a logical vector in which the
TRUE values correspond to the "Count" values with a type of "A" that
are less than the maximum value for type "B" count values". The
expression within the first pair of extraction operators can be
translated, "Extract all of the values of "Count" with a type of "A"
in the current row". So, the second extraction then operates on those
values, producing a vector of all of the "Count" values that are less
than the value of "maxB". The line following this in the code uses the
same logic to extract those values that are greater than or equal to
"maxB".

Jim

On Thu, Apr 21, 2016 at 11:25 PM, sri vathsan <srivibish at gmail.com> wrote:
> Dear Jim,
>
> I hope, I am not pestering you. When I was studying your code to grasp and
> learn and found one thing which I can not understand the following line. I
> would be grateful If you could tell what it exactly denote and this helps me
> to grow better in R.
>
> I understand the first part of the code will check the rows of indicesA, but
> I finding difficulty to grasp the second part starting with the square
> bracket.
>
> "AltB<-svdatstr[row,indicesA][svdatstr[row,indicesA]"
>



More information about the R-help mailing list