Subscript type for remove an Array column from index in R

huangapple go评论68阅读模式
英文:

Subscript type for remove an Array column from index in R

问题

可以用作从n维数组中删除列的索引参数是一个矩阵(matrix)。以下是您提供的R代码的翻译部分:

deleteCol <- function(array, col_to_del, in_dim) {
  index <- vector(mode = 'list', length = length(dim(array)))
  index[in_dim] <- -col_to_del
  return(array[index, drop = FALSE])
}

希望这对您有所帮助。

英文:

What kind of object can I use as an index argument to remove columns from an n-dim array?

deleteCol &lt;- function(array,col_to_del,in_dim){
	index &lt;- vector(mode=&#39;list&#39;, length=length(dim(array)))
	index[in_dim] &lt;- -col_to_del
	return(array[index, drop = FALSE])
}

I want to make a function that removes a specific column from an array, and I want to make this work for any n-dimension arrays. I already know that lists aren't accepted as index arguments, but matrix does. The code is just to show what I want to do. I don't find that an index matrix does the job because I can't enter negative or NULL values required for indexes like " , , ... , -n, ... ,".

I try to make an index matrix, but it doesn't accept negative elements, nor does it have an element to leave an empty position.

答案1

得分: 0

Oh, codey-wodey! This looks like a puzzling language to me, but I'll try my best to help!

Here's the code part without translation:

a <- array(1:32, dim=c(2,2,2,2))
dim(a)
##[1] 2 2 2 2
qeo <- list(quote(expr=))
args <- c(qeo, -1, rep(qeo, length(dim(a))-2), drop = FALSE)
out <- do.call(`[`, c(list(a), args))
dim(out)
##[1] 2 1 2 2

removecol <- function(array, col_to_del, in_dim){   
    qeo <- list(quote(expr=))
    qeo <- rep(qeo, length(dim(array)))
    qeo[in_dim] <- -col_to_del
    args <- c(qeo, drop = FALSE)
    do.call(`[`, c(list(array), args))
}

I hope that helps, even though it's like a magical incantation from a wizard's spellbook! 😄✨

英文:

This is extraordinarily ugly, but here's a way to pass the empty arguments to drop columns programmatically from an n-dimensional array:

a &lt;- array(1:32, dim=c(2,2,2,2))
dim(a)
##[1] 2 2 2 2
qeo &lt;- list(quote(expr=))
args &lt;- c(qeo, -1, rep(qeo, length(dim(a))-2), drop = FALSE)
out &lt;- do.call(`[`, c(list(a), args))
dim(out)
##[1] 2 1 2 2

Put into a flexible function by @magavich, from the comments:

removecol &lt;- function(array, col_to_del, in_dim){   
    qeo &lt;- list(quote(expr=))
    qeo &lt;- rep(qeo, length(dim(array)))
    qeo[in_dim] &lt;- -col_to_del
    args &lt;- c(qeo, drop = FALSE)
    do.call(`[`, c(list(array), args))
}

huangapple
  • 本文由 发表于 2023年7月17日 11:08:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定