![]() |
Introduction
To R |
> x <- 10:1 > y <- x[2] > y [1] 9Here y gets the value of the second element of x.
> y <- x[c(1,3,5)] > y [1] 10 8 6 > x[4:7] [1] 7 6 5 4Here the returned value is a vector.
> x[12] [1] NAyou get NA. This is the symbol R uses for missing data, or other numeric nonsense.
> x <- c(6,5,6,4,4,3,4,2,3,4) > y <- c(5,3,4,2,6,5,4,5,4,3) couple of random vectors > xeq4 <- x == 4 which of x equals 4 > xeq4 [1] FALSE FALSE FALSE TRUE TRUE FALSE TRUE FALSE FALSE TRUE > y[xeq4] which of y correspond to [1] 2 6 4 3 x==4? > y[x == 4] [1] 2 6 4 3 or simply...
> x <- 1:10 > x[-3] [1] 1 2 4 5 6 7 8 9 10 missing 3 > x[c(3,4,7)] [1] 3 4 7 > x[-c(3,4,7)] a vector of negatives [1] 1 2 5 6 8 9 10You can't mix positive and negative subscripts. Why would you want to?
> x <- 1:10 > x[-length(x)] all but the last [1] 1 2 3 4 5 6 7 8 9 > x[length(x):1] reverse x [1] 10 9 8 7 6 5 4 3 2 1There is a function to do this last one: rev(x) - most of the simple things you may want to do tend to have their own functions!
Later you will learn to use the help system to find them.
> x <- 1:4 > y <- 8:11 > z2 <- complex(r=x,i=y) > z2 [1] 1+ 8i 2+ 9i 3+10i 4+11i > z2[1]+z2[2] [1] 3+17i