Load kidney data.
data(kidney)
head(kidney)
id time status age sex disease frail
1 1 8 1 28 1 Other 2.3
2 1 16 1 28 1 Other 2.3
3 2 23 1 48 2 GN 1.9
4 2 13 0 48 2 GN 1.9
5 3 22 1 32 1 Other 1.2
6 3 28 1 32 1 Other 1.2
kidney.transformed <- transform(kidney,
age.10 = age * 10
)
head(kidney.transformed)
id time status age sex disease frail age.10
1 1 8 1 28 1 Other 2.3 280
2 1 16 1 28 1 Other 2.3 280
3 2 23 1 48 2 GN 1.9 480
4 2 13 0 48 2 GN 1.9 480
5 3 22 1 32 1 Other 1.2 320
6 3 28 1 32 1 Other 1.2 320
A variable created in the transformation process cannot be used.
The example below fails.
if(FALSE) {
kidney.transformed.2 <- transform(kidney,
age.10 = age * 10,
age.100 = age.10 * 10
)
head(kidney.transformed.2)
}
A variable created in the transformation process (age.10) can be used.
{ } is required. <- or = can be used. No , is necessary.
The variable created first is found in the rightmost column.
kidney.withined <- within(kidney, {
age.10 <- age * 10
age.100 <- age.10 * 10
})
head(kidney.withined)
id time status age sex disease frail age.100 age.10
1 1 8 1 28 1 Other 2.3 2800 280
2 1 16 1 28 1 Other 2.3 2800 280
3 2 23 1 48 2 GN 1.9 4800 480
4 2 13 0 48 2 GN 1.9 4800 480
5 3 22 1 32 1 Other 1.2 3200 320
6 3 28 1 32 1 Other 1.2 3200 320
plyr::mutate is similar to within().
However { } and <- cannot beused, thus , is required after each line.
The variable created last is found in the rightmost column.
library(plyr)
kidney.mutated <- mutate(kidney,
age.10 = age * 10,
age.100 = age.10 * 10
)
head(kidney.mutated)
id time status age sex disease frail age.10 age.100
1 1 8 1 28 1 Other 2.3 280 2800
2 1 16 1 28 1 Other 2.3 280 2800
3 2 23 1 48 2 GN 1.9 480 4800
4 2 13 0 48 2 GN 1.9 480 4800
5 3 22 1 32 1 Other 1.2 320 3200
6 3 28 1 32 1 Other 1.2 320 3200