【问题标题】:use psych reverse.code() on dataframe in R在 R 中的数据帧上使用 psych reverse.code()
【发布时间】:2020-02-17 19:07:52
【问题描述】:

我正在尝试在具有数字和非数字列的数据框中的一列上使用 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)

【问题讨论】:

    标签: r dataframe reverse psych


    【解决方案1】:

    如果我们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
    

    或者%&gt;%

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

    【讨论】:

      【解决方案2】:

      这个话题可能很老了,但我遇到了同样的问题,@akrun 的解决方案在技术上是可行的,但最后,你没有得到一个数据框作为输出,因此无法进行进一步的计算。

      首先,正如您所说的与学生一起工作,您的数据可能如下所示:

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

      这对学生来说阅读起来更加直观(但只是一个加法,不会改变结果)。


      @akrun 给出的解决方案确实是正确的。但是,您需要最后的名称,因为在这里您想知道谁获得了哪个分数(或者通常您可能希望通过 ID 作为键将结果绑定到数据集)。因此,以下内容也可能对您有用:

      1. 将名称(或 ID)保存为行名
      2. 运行reverse.code()函数
      3. 转换结果以通过以下方式将行名作为列返回

      确保在第 3 步中使用as.data.frame(),因为as_tibble() 将忽略名称。

      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
      

      【讨论】:

        猜你喜欢
        • 2020-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多