0

I've searched several help-pages and already answered questions but still get an error message when I try to recode multiple columns.

Example dataset:

test <- tibble (
  a_test = c(7,6,5,4),
  b_test = c(7,7,5,3),
  c_test = c(7,3,7,5),
  d_test = c(7,7,7,7)
)

test %>%
  mutate(across(vars(contains('test')), recode, "1" = "7", "2" = "6", "3" = "5", "4" = "4", "5" = "3", "6" = "2", "7" = "1")

Once I run this code, I get the following error message:

Error in mutate(): ! Problem while computing ..1 = across(...). Caused by error in across(): ! Must subset columns with a valid subscript vector. x Subscript has the wrong type quosures. i It must be numeric or character.

I'd really appreciate your help. Thanks in advance!

joh_anna
  • 11
  • 2
  • Can you make your post [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and provide your data using `dput(dataset)`? Also please be aware that [`mutate_at` has been superseded](https://dplyr.tidyverse.org/reference/mutate_all.html). – jrcalabrese Jan 07 '23 at 15:21
  • I've changed my question and the code, hope this clarifies my problem? – joh_anna Jan 07 '23 at 15:31

1 Answers1

0

You should remove the vars argument, add a tilde (~), and begin your recode statement with .x.

On 1/25/23, I updated my answer to include a full reprex with my R version and dplyr package version. I also added the as.numeric() wrapper to ensure that the recoded values stay numeric after recoding.

library(dplyr)
R.version$version.string
#> [1] "R version 4.2.2 (2022-10-31)"
packageVersion("dplyr")
#> [1] '1.0.10'

test <- tibble(
  a_test = c(7,6,5,4),
  b_test = c(7,7,5,3),
  c_test = c(7,3,7,5),
  d_test = c(7,7,7,7)
)
sapply(test, class)
#>    a_test    b_test    c_test    d_test 
#> "numeric" "numeric" "numeric" "numeric"

test2 <- test %>%
  mutate(across(contains("test"), ~
                  as.numeric(recode(.x, "1" = "7", "2" = "6", "3" = "5", "4" = "4", "5" = "3", "6" = "2", "7" = "1"))))
                
head(test2)
#> # A tibble: 4 × 4
#>   a_test b_test c_test d_test
#>    <dbl>  <dbl>  <dbl>  <dbl>
#> 1      1      1      1      1
#> 2      2      1      5      1
#> 3      3      3      1      1
#> 4      4      5      3      1
sapply(test2, class)
#>    a_test    b_test    c_test    d_test 
#> "numeric" "numeric" "numeric" "numeric"
jrcalabrese
  • 2,184
  • 3
  • 10
  • 30