R: Data Manipulation
Code Only
|
Code with Rweb Output
|
x=c(1,3,2,10,5) #create a vector x with 5 components
x y=1:5 #create a vector of consecutive integers y y+4 #scalar addition 3*y #scalar multiplication y^3 #raise each component to the third power 2^y #raise 3 to the first through fifth power y #y itself has not been unchanged y = y*2 #it is now changed y #it is now changed x+y # add x and y x*y # multiply x and y x/y # divide x and y x^y # raise each x term to the corresponding y term z=x+y # add x and y, then assign to term z z # request sum(x) #sum of elements in x cumsum(x) #cumulative sum vector diff(x) # first difference diff(x,2) #second difference max(x) #maximum min(x) #minimum ### Sort your data x sort(x) # increasing order sort(x, decreasing=T) # decreasing order ### Component extraction is a very important part of vector calculation. x length(x) # number of elements in x x[4] # the fourth element of x x[2:5] # the second to fifth element of x, inclusive x[-2] # all except the second element x[x>3] # list of elements in x greater than 3 ### Logical vector can be handy: x>3 # Which x values are greater than 3 sum(x>3) # number of elements in x greater than 3 |
> x=c(1,3,2,10,5) #create a vector x with 5 components
> x [1] 1 3 2 10 5 > y=1:5 #create a vector of consecutive integers > y [1] 1 2 3 4 5 > y+4 #scalar addition [1] 5 6 7 8 9 > 3*y #scalar multiplication [1] 3 6 9 12 15 > y^3 #raise each component to the third power [1] 1 8 27 64 125 > 2^y #raise 3 to the first through fifth power [1] 2 4 8 16 32 > y #y itself has not been unchanged [1] 1 2 3 4 5 > y = y*2 #it is now changed > y #it is now changed [1] 2 4 6 8 10 > x+y # add x and y [1] 3 7 8 18 15 > x*y # multiply x and y [1] 2 12 12 80 50 > x/y # divide x and y [1] 0.5000000 0.7500000 0.3333333 1.2500000 0.5000000 > x^y # raise each x term to the corresponding y term [1] 1 81 64 100000000 9765625 > z=x+y # add x and y, then assign to term z > z # request [1] 3 7 8 18 15 > > sum(x) #sum of elements in x [1] 21 > cumsum(x) #cumulative sum vector [1] 1 4 6 16 21 > diff(x) # first difference [1] 2 -1 8 -5 > diff(x,2) #second difference [1] 1 7 3 > max(x) #maximum [1] 10 > min(x) #minimum [1] 1 > > ### Sort your data > x [1] 1 3 2 10 5 > sort(x) # increasing order [1] 1 2 3 5 10 > sort(x, decreasing=T) # decreasing order [1] 10 5 3 2 1 > > ### Component extraction is a very important part of vector calculation. > x [1] 1 3 2 10 5 > length(x) # number of elements in x [1] 5 > x[4] # the fourth element of x [1] 10 > x[2:5] # the second to fifth element of x, inclusive [1] 3 2 10 5 > x[-2] # all except the second element [1] 1 2 10 5 > x[x>3] # list of elements in x greater than 3 [1] 10 5 > > ### Logical vector can be handy: > x>3 # Which x values are greater than 3 [1] FALSE FALSE FALSE TRUE TRUE > sum(x>3) # number of elements in x greater than 3 [1] 2 |
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.