Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何返回具有2个以上唯一值的所有行?_R - Fatal编程技术网

R 如何返回具有2个以上唯一值的所有行?

R 如何返回具有2个以上唯一值的所有行?,r,R,现在我有一个名为最近的向量。labels,其中包含以下数据: [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 2 2 2 2 2 2 2 2 2 2 [2,] 0 0 0 0 0 0 0 0 0 0 [3,] 9 9 9 9 9 9 9 7 7

现在我有一个名为
最近的向量。labels
,其中包含以下数据:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    2    2    2    2    2    2    2    2    2     2
[2,]    0    0    0    0    0    0    0    0    0     0
[3,]    9    9    9    9    9    9    9    7    7     4
我想做的是返回行数据以及有两个以上唯一值的行的索引。在上面的示例中,这只是第三行。到目前为止,我已经部分成功地使用了
apply
和我创建的函数。见下文:

colCountFx <- function(col){
    result <- subset(list(index=col,count=length(unique(col))),length(unique(col))>2)
    return(result)
}
apply(closest.labels,1, colCountFx)
对于当前返回
命名列表()
的行,我需要更改什么以不返回任何内容?另外,我对R还比较陌生,所以如果你认为有更好的方法,我也愿意接受

>ind
> ind <- apply(x, 1, function(x) length(unique(x)))
> ind
[1] 1 1 3
[1] 1 1 3
>ind ind
[1] 1 1 3

您可以使用另一个索引来删除空列表。说:

remaining <- apply(closest.labels,1, colCountFx)
remaining.ind <- sapply(remaining,length) != 0
remaining[remaining.ind]

剩余您可以使用另一个索引来删除空列表。说:

remaining <- apply(closest.labels,1, colCountFx)
remaining.ind <- sapply(remaining,length) != 0
remaining[remaining.ind]

remaining您可以使用跨行应用的
unique
项的
length
获取索引
mat
将用作包含项目的矩阵的名称

nUnique <- apply( mat, 1, function(x) length(unique(x)) )
ind <- which(nUnique > 2)

您可以使用跨行应用的
unique
项的
length
获取索引
mat
将用作包含项目的矩阵的名称

nUnique <- apply( mat, 1, function(x) length(unique(x)) )
ind <- which(nUnique > 2)

如果你想要的是
列表
,你可以试试这样的东西。不过,就我个人而言,我觉得嵌套列表有些麻烦

首先,一些数据(为了清晰起见,我增加了一行):


如果你想要的是
列表
,你可以试试这样的东西。不过,就我个人而言,我觉得嵌套列表有些麻烦

首先,一些数据(为了清晰起见,我增加了一行):


是否必须将输出放在嵌套列表中,每个元素都包含
索引
计数
子元素?是否必须将输出放在嵌套列表中,每个元素都包含
索引
计数
子元素?我没有设置在嵌套列表中,在你看来,什么是更好的选择?我没有被设置在嵌套列表上,在你看来,什么是更好的选择?
mat[ind,]
closest.labels <- structure(c(2, 0, 9, 8, 2, 0, 9, 8, 2, 0, 9, 8, 2, 0, 9, 8, 2, 
                              0, 9, 8, 2, 0, 9, 5, 2, 0, 7, 6, 2, 0, 7, 7, 2, 0, 
                              4, 8, 2, 0, 4, 9), .Dim = c(4L, 10L))
colCountFx <- function(data) {
  temp = apply(data, 1, function(x) length(unique(x)))
  result = which(temp > 2)
  out = vector("list")
  for (i in 1:length(result)) {
    out[[i]] = list(index = data[result[i], ], count = temp[result[i]])
  }
  names(out) = paste("row", result, sep = "_")
  out
}
colCountFx(closest.labels)
# $row_3
# $row_3$index
# [1] 9 9 9 9 9 9 7 7 4 4
# 
# $row_3$count
# [1] 3
# 
# 
# $row_4
# $row_4$index
# [1] 8 8 8 8 8 5 6 7 8 9
# 
# $row_4$count
# [1] 5