【问题标题】:"R" Warning message: In mapply longer argument not a multiple of length of shorter“R”警告消息:在 mapply 较长的参数中不是较短长度的倍数
【发布时间】:2021-09-04 00:56:36
【问题描述】:

我正在尝试制作一个简单的函数来反转我的 R 数据框中的多个列的代码。我正在使用 lapply 和 mapply 在函数中,这似乎给了我预期的结果,除了警告消息

Warning message:
In mapply("-", max_value, data[, rev]) :
  longer argument not a multiple of length of shorter

为了说明,这里有一些示例数据

{
A = c(3, 3, 3, 3, 3, 3, 3, 3, 3, 3)
B = c(9, 2, 3, 2, 4, 0, 2, 7, 2, 8)
C = c(2, 4, 1, 0, 2, 1, 3, 0, 7, 8)

df1 = data.frame(A, B, C)
print(df1)
}
   A B C
1  3 9 2
2  3 2 4
3  3 3 1
4  3 2 0
5  3 4 2
6  3 0 1
7  3 2 3
8  3 7 0
9  3 2 7
10 3 8 8

反码函数如下:

## columns to reverse-code
revcode_cols = c("A", "B")

## function to reverse code variables
reverseCode <- function(data, rev){
  
  # get maximum value per column 
  max_value = lapply(data, max)
  
  # subtract values in designated cols from max value plus 1
  data[, rev] = mapply("-", max_value, data[, rev]) + 1
  
  return(data)
  
}

reverseCode(df1, revcode_cols)

   A  B C
1  1  1 2
2  1  8 4
3  1  7 1
4  1  8 0
5  1  6 2
6  1 10 1
7  1  8 3
8  1  3 0
9  1  8 7
10 1  2 8

它给出了正确的输出,但对于警告消息。只是想知道我需要修复脚本的哪一部分以消除警告消息。

【问题讨论】:

    标签: r apply mapply


    【解决方案1】:

    data.frame 的单位是列,vector 的单位是单个元素。在mapply/Map 中,我们传递了两个输入,但在OP 的代码中,max 是在整个数据集上计算的,创建了一个'max_value' 作为list 的3 个元素,data[, rev] 属于长度 2. 我们只需要对数据进行子集化即可计算max

    reverseCode <- function(data, rev){
      
      # get maximum value per column 
      max_value = lapply(data[rev], max)
      
      # subtract values in designated cols from max value plus 1
      data[, rev] = mapply("-", max_value, data[, rev]) + 1
      
      return(data)
      
    }
    

    -测试

    reverseCode(df1, revcode_cols)
       A  B C
    1  1  1 2
    2  1  8 4
    3  1  7 1
    4  1  8 0
    5  1  6 2
    6  1 10 1
    7  1  8 3
    8  1  3 0
    9  1  8 7
    10 1  2 8
    

    【讨论】:

      【解决方案2】:

      您可以在一个lapply 中执行此操作,而不是使用两个应用循环。

      reverseCode <- function(data, rev){
        data[rev] <- lapply(data[rev], function(x) max(x) - x + 1)
        data
      }
      
      reverseCode(df1, c("A", "B"))
      
      #   A  B C
      #1  1  1 2
      #2  1  8 4
      #3  1  7 1
      #4  1  8 0
      #5  1  6 2
      #6  1 10 1
      #7  1  8 3
      #8  1  3 0
      #9  1  8 7
      #10 1  2 8
      

      【讨论】:

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