Home > OS >  R : y[x] & x[y] when x,y vectors
R : y[x] & x[y] when x,y vectors

Time:02-08

Silly question but for real i cant undestand what is happening here (Screenshot) ,especially in x[y]. In y[x] i undestand that he is getting the similar objects for x & y. But in x[y] he is getting objects that y is not having enter image description here

CodePudding user response:

x[y] is looking for the y'th index in x. Essentially it is looking for elements 1,2,3,4,5,6,7 in x, which correspond to the first 7 elements in x. Hence x[y] just returns the contents of x.

y[x] is looking for the x'th index in y - that is the 2nd, 4th, 6th, 8th etc up to 14th indexes. But since y is only 7 elements long, everything after that just returns NA, because there is no 8th index in y, and so on.

CodePudding user response:

Data

x
[1]  2  4  6  8 10 12 14

y
[1] 1 2 3 4 5 6 7

Explanation

The following returns the yth position of x, which is in this case, the first 7 elements of x (note that the first element of a vector in R has an index of 1 but not 0)

x[y]
[1]  2  4  6  8 10 12 14

Similarly, this returns the xth position of y, which is the second, the 4th ... and the 14th element of y. However, since y only has 7 elements, it returns missing values (NA) after the seventh index.

y[x]
[1]  2  4  6 NA NA NA NA

CodePudding user response:

When you ask x[y] (respectively y[x]), you are actually asking the "yth" (resp. "xth") values of x (resp. y).

For instance :

> x <- c(1, 4)
> y <- c(10, 20, 35, 70)
> y[x]
[1] 10 70

y[x] returns values of y at positions 1 and 4.

> y[c(x, 10)]
[1] 10 70 NA

y[c(x, 10)] returns values of y at positions 1 and 4 and 10. The 10th value is missing, so it returns NA.

  •  Tags:  
  • Related