为输入碰巧是向量时工作的表编写泛型函数 [英] Writing generic function for tables that works when the input happens to be vector

查看:131
本文介绍了为输入碰巧是向量时工作的表编写泛型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<2D>将2D data.frame 矩阵自动转换为1D向量也很好,编写通用函数。例如,试图使用像 foo [,1:3] 这样的命令过滤输入 foo 的某些列可以正常工作对于 data.frame 矩阵

<$ p $ ($ 1 $ 9 $ n $ = 3)
bar = function(x)print(x [,1])$ ​​b $ b bar(foo)#[1] 1 2 3

但考虑我们首先要过滤 foo ,而且恰好只有一行保留:

  bar(foo [1,])# x [,1]中的错误:维数不正确

这个问题可以通过一个简单的技巧来解决:

  bar = function(x){
if(is.null(dim(x)))x = t(data.frame(x))
print(x [,1])$ ​​b $ b}

但是如果我们在 bar() x 其他过滤器,问题会更加复杂$ c>,可能会再次将其转换为矢量。然后,我们应该检查每个过滤器,并确保我们所拥有的仍然是一张表。



其他问题是:如果缺少行名称和/或列名称if矩阵的过滤部分仅为单行/列。它需要进一步的操作来将过滤后的部分重新组织为一个矩阵,检索原始的行/列名并将它们分配给结果矩阵。



问题是:如何简单转换一个适用于表的通用函数,如果输入恰好是向量,它仍然有效?

解决方案

在处理可能是向量或data.frame的数据时,我遇到了类似的问题。

通常,我只是在函数内创建一个子集函数。

  foo < - 函数(dat,rows){

if(is.data.frame (dat)|| is.matrix(dat)){
dat <-dat [rows,]
} else else {
dat <-dat [rows]

...#继续使用函数
}

此方法也维护类的原始对象。

The automatic conversion of 2D data.frame or matrix to 1D vectors, also good, makes some problems while writing generic functions. For example trying to filter some columns of the input foo with a command like foo[,1:3] works fine for a data.frame or matrix:

foo=matrix(1:9,nrow=3)
bar = function(x) print(x[,1])
bar(foo) # [1] 1 2 3

But consider we first want to filter some rows of foo, and it happens that only a single row remains:

bar(foo[1,]) # Error in x[, 1] : incorrect number of dimensions

This problem may be solved by a simple trick:

bar = function(x) {
    if (is.null(dim(x))) x = t(data.frame(x))
    print(x[,1])
}

But the problem would be much more complicated if we have other filters on x in the body of bar() that may convert it again to a vector. Then for every filtering we should check and do the same to ensure what we have is still a table.

The other problems are: missing row names and/or column names if the filtered part of a matrix is only a single row/column. It needs further manipulation to re-organize the filtered part as a matrix, retrieve the original row/column names and assign them to the resulting matrix.

The question is that: How to simply convert a function that works for tables a generic one, that if the input happens to be vector it still works?

解决方案

I have similar problems when working with data that could be a vector or a data.frame.

Usually, I just create a subset function within the function.

foo <- function(dat,rows) { 

if(is.data.frame(dat) || is.matrix(dat)) { 
dat <- dat[rows,] 
} else {
dat <- dat[rows]

... # continue with function
}

This method also maintains the class of the original object.

这篇关于为输入碰巧是向量时工作的表编写泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆