2

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)
J.Sabree
  • 2,280
  • 19
  • 48

2 Answers2

2

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

This topic might be old, but I had the same problem and @akrun's solution technically works, but in the end, you don't get a dataframe as an output and therefore can't do further calculations.

First, as you say you are working with students, your data might look like this:

library(tibble)

sample <- tribble(~name, ~item_1, ~item_2, ~item_3,
                  'Joe',    1,       1,       5,
                  'Frank',  1,       1,       5)

key <- c(1, 1, -1) 

This is far more intuitive for students to read (but only an addition, it does not change the result).


The solution given by @akrun is indeed correct. However, you need the name at the end, because here you want to know who has got which score (or in general you might want to bind the outcome to a dataset by ID as key). Therefore, the following might work for you as well:

  1. save the name (or ID) as the row name
  2. run the reverse.code() function
  3. transform the outcome to get the row name back as a column via

Make sure to use as.data.frame() in step 3 because as_tibble() will ignore the names.

library(psych)
library(dplyr)

sample %>% 
  column_to_rownames(var = "name") %>% 
  reverse.code(keys = key, items = ., mini = 1, maxi = 5) %>% 
  as.data.frame() %>% 
  rownames_to_column(var = "name") -> sample_inv
J-WoW
  • 11
  • 1
  • 4