首页 > 解决方案 > 在 R 中的数据帧上使用 psych reverse.code()

问题描述

我正在尝试在具有数字和非数字列的数据框中的一列上使用 psych 包中的 reverse.code()。但是,当我尝试执行此操作时,出现错误:

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

您对如何完成这项工作有任何建议吗?我正在为我的 R 功能差异很大的学生制作教程,所以代码越简单越好。这是一个给出相同错误的模拟数据集:

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)

标签: rdataframereversepsych

解决方案


如果我们select的数据不包括第一列即character列,它应该可以工作

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

或者在一个%>%

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

推荐阅读