【问题标题】:Write a general function in R that returns the line number of a specific vector在 R 中编写一个通用函数,返回特定向量的行号
【发布时间】:2021-04-09 08:52:21
【问题描述】:

我构建了一些基于样本的数据框:

library(DescTools)

N <- 5
C <- 4

y <- CombSet(0:(C - 1), N, repl = TRUE, ord = FALSE)
data_y <- data.frame(y)

data_y_sort <- data_y[rev(order(rowSums(data_y), decreasing = T)), ]

x <- matrix(, nrow = choose(N + C - 1, C - 1), ncol = C)

for (i in 1:choose(N + C - 1, C - 1)) {
  for (j in 0:(C - 1)) {
    x[i, (j + 1)] <- sum(data_y_sort[i, ] == j)
  }
}

data <- data.frame(x)

我现在正在尝试编写一个通用函数,它返回我的数据行与某个向量a 相同的行或“行”号。例如,对于我的示例数据,当向量 c(3,2,0,0) 作为参数传递时,函数应该返回 3,因为它出现在 x 的第 3 行。

也就是说,我需要将 x 行中的每个元素与函数中的参数进行比较,它会返回相应的行。

我尝试的是:

new.function1 <- function(a) {
    result <- which(data[,i]==a[i])
    print(result)
}

我也试过

new.function2 <- function(a) {
    result <- which(for(i in 1:C){identical(data[,i],a[i])})
    print(result)
}

很遗憾,它们都不起作用。

【问题讨论】:

  • which(x == 4, arr.ind = T) 将返回包含值 4 的行和列索引。你想要这样的东西吗?您可以像这样索引行:x[which(x == 4, arr.ind = T)[,1],]。您在第一个函数中的索引不起作用,因为您尚未定义 i。我认为您也不希望在第二个 which 中使用 for 循环 :)

标签: r


【解决方案1】:

也许这就是你要找的。​​p>

new.function <- function(x, a) {
  which(rowSums(as.matrix(x) == matrix(a, nrow = nrow(x), ncol = ncol(x), byrow = TRUE)) == ncol(x))
}

a <- c(3, 2, 0, 0)

new.function(data, a)
#> [1] 3

数据

data <- structure(list(X1 = c(
  5L, 4L, 3L, 4L, 2L, 3L, 4L, 1L, 2L, 3L,
  3L, 0L, 1L, 2L, 2L, 3L, 0L, 1L, 1L, 2L, 2L, 3L, 0L, 0L, 1L, 1L,
  2L, 2L, 0L, 0L, 1L, 1L, 1L, 2L, 0L, 0L, 0L, 1L, 1L, 2L, 0L, 0L,
  0L, 1L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L
), X2 = c(
  0L,
  1L, 2L, 0L, 3L, 1L, 0L, 4L, 2L, 0L, 1L, 5L, 3L, 1L, 2L, 0L, 4L,
  2L, 3L, 0L, 1L, 0L, 3L, 4L, 1L, 2L, 0L, 1L, 2L, 3L, 0L, 1L, 2L,
  0L, 1L, 2L, 3L, 0L, 1L, 0L, 0L, 1L, 2L, 0L, 1L, 0L, 1L, 2L, 0L,
  0L, 1L, 0L, 0L, 1L, 0L, 0L
), X3 = c(
  0L, 0L, 0L, 1L, 0L, 1L, 0L,
  0L, 1L, 2L, 0L, 0L, 1L, 2L, 0L, 1L, 1L, 2L, 0L, 3L, 1L, 0L, 2L,
  0L, 3L, 1L, 2L, 0L, 3L, 1L, 4L, 2L, 0L, 1L, 4L, 2L, 0L, 3L, 1L,
  0L, 5L, 3L, 1L, 2L, 0L, 4L, 2L, 0L, 1L, 3L, 1L, 0L, 2L, 0L, 1L,
  0L
), X4 = c(
  0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L,
  0L, 1L, 1L, 0L, 0L, 1L, 0L, 1L, 2L, 0L, 1L, 0L, 1L, 1L, 2L, 0L,
  1L, 0L, 1L, 2L, 2L, 0L, 1L, 2L, 1L, 2L, 3L, 0L, 1L, 2L, 2L, 3L,
  1L, 2L, 3L, 3L, 2L, 3L, 4L, 3L, 4L, 4L, 5L
)), class = "data.frame", row.names = c(
  NA,
  -56L
))

【讨论】:

  • 这太完美了!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
相关资源
最近更新 更多