rdataframereversepsych

use psych reverse.code() on dataframe in R


I'm trying to use reverse.code() from the psych package on one column in a dataframe that has numeric and non-numeric columns. However, when I try to do this, I get an error:

Error in items %*% keys.d : 
  requires numeric/complex matrix/vector arguments

Do you have any suggestions on how to make this work? I am making a tutorial for my students who vary greatly in their R capabilities, so the simpler the code, the better. Here is a mock dataset that gives the same error:

sample <- tibble(name = c("Joe", "Frank"),
                 item_1 = c(1, 1),
                 item_2 = c(1, 1),
                 item_3 = c(5, 5))

key <- c("item_3")
reverse.code(keys = key, items = sample, mini = 1, maxi = 5)

Solution

  • If we select the data without including the first column i.e. character column, it should work

    library(psych)
    reverse.code(keys = key, items =sample[-1], mini = 1, maxi = 5)
    #    item_1 item_2 item_3-
    #[1,]      1      1       1
    #[2,]      1      1       1
    

    Or in a %>%

    library(dplyr)
    sample %>%
        select_if(is.numeric) %>%
        reverse.code(keys  = key, items = ., mini = 1, maxi = 5)