I have a data frame with x columns. From each column, I want to create a new column, where data are replaced by their ranks, but the ranks are not standard but follow a pyramid style.
To do this, I am tryng to use mutate within a function and loop that function over the different columns.
I have tried this in different ways. However, I keep on getting an error (see below code) and I do not understand why I get that error.
df <- tibble(Z1 = rnorm(40), Z2 = rnorm(40))
pyramid = c(rep(5,2),rep(4,3),rep(3,3), rep(2,4), rep(1,5), rep(0,6),
rep(-1, 5), rep(-2,4), rep(-3, 3), rep(-4,3), rep(-5,2))
for (i in 1:2){
Z <- rlang::sym(paste("Z", i, sep=""))
QS <- rlang::sym(paste("QS", i, sep=""))
df <- df %>% arrange(!!-Z) %>% mutate(!!QS = pyramid)
}
The error:
Error: unexpected '=' in:
"
df <- df %>% arrange(!!-Z) %>% mutate(!!QS ="
> }
Error: unexpected '}' in "}"
Since the following code is working, I suspect it comes from the way I use a symbol to create a new variable. I have also tried using a String and got the same error. I have also tried the double curly instead of the double !! and it got the same issue So I am lost!
for (i in 1:2){
Z <- rlang::sym(paste("Z", i, sep=""))
df <- df %>% arrange(!!-Z) %>% mutate(QS2 = pyramid)
}
The expected output should look like this:
# A tibble: 40 x 4
Z1 Z2 QS1 QS2
<dbl> <dbl> <dbl> <dbl>
1 -0.591 1.64 -2 5
2 -0.132 1.59 0 5
3 -0.418 1.59 -2 4
4 1.11 1.52 4 4
5 1.65 1.15 4 4
6 0.289 1.11 1 3
7 1.85 1.09 5 3
8 0.526 1.07 1 3
9 -0.436 1.04 -2 2
10 -0.671 0.794 -3 2
# ... with 30 more rows
pyramidused for?:=, i.e.mutate(!!QS := pyramid).