Variable transformations

TODO

  • link to recode, dataFrames

Install required packages

car

Convert between data types

Type hierarchy

Lower types can be uniquely converted to higher types.

[1] 1 0 0 1
[1] 1+0i 0+0i 0+0i 1+0i
[1] "TRUE"  "FALSE" "FALSE" "TRUE" 

Higher types cannot be uniquely converted to lower types.

[1]  TRUE FALSE  TRUE  TRUE
Warning: imaginary parts discarded in coercion
[1] 3 3 0 0
Warning: NAs introduced by coercion
[1] 21.000  3.141     NA

Change order of vector elements

Sort vectors

 [1] 20 19 18 17 16 15 14 13 12 11 10
 [1]  1  6  7 10 10 12 12 16 19 19
 [1]  8 10  6  2  4  1  9  5  7  3
 [1] 19 19 16 12 12 10 10  7  6  1
 [1] "10" "4"  "A"  "A"  "D"  "D"  "E"  "E"  "E"  "F" 

Randomly permute vector elements

[1] "blue"   "green"  "black"  "yellow" "red"   
 [1] 1 1 1 1 2 2 2 3 3 3 3 3
 [1] 2 3 2 1 3 3 1 1 1 2 3 3

Randomly place elements in \(p\) groups of approximately equal size

 [1] 1 2 2 3 1 3 1 2 3 2

Select random or systematic subsets of vector elements

Random selection

[1] "red"   "red"   "green" "green" "green"
[1] "red"  "red"  "blue" "blue" "blue"

Select every 10th element

[1] "red"   "green" "blue" 

Select approximately every 10th element

character(0)

Transform old variables into new ones

Element-wise arithmetic

[1] 1.8 2.0 3.0 2.4 2.3 2.1
[1] 14.0 15.0 20.0 17.0 16.5 15.5
[1]  -6   8 -10  12
[1] 1e-01 6e-02 3e-03 8e-04

Recycling rule

[1]  6 12  5
 [1]  36  80 180 192 230 252 252 320 540 480 506 504
Warning in vec2 * age: longer object length is not a multiple of shorter object
length
[1]  36  80 180 192 230  42

Standardize variables

[1] -1.1166106 -0.6380632  1.7546739  0.3190316  0.0797579 -0.3987895
           [,1]
[1,] -1.1166106
[2,] -0.6380632
[3,]  1.7546739
[4,]  0.3190316
[5,]  0.0797579
[6,] -0.3987895
attr(,"scaled:center")
[1] 22.66667
attr(,"scaled:scale")
[1] 4.179314
[1] -1.1166106 -0.6380632  1.7546739  0.3190316  0.0797579 -0.3987895

Move and scale variable

[1]  83.25084  90.42905 126.32011 104.78547 101.19637  94.01816
[1] 100
[1] 15

Rank transformation

[1] 3.5 1.0 2.0 3.5

Transform old variables into new ones

[1] 20.51509 24.39626 25.47521 22.39541 27.14158
[1] 2 1 1 2 1 3 1 1

Detach (automatically) loaded packages (if possible)

Get the article source from GitHub

R markdown - markdown - R code - all posts