Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.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
对于data.frame中的每一列,查找列是唯一具有正值的行_R_Dataframe_Unique - Fatal编程技术网

对于data.frame中的每一列,查找列是唯一具有正值的行

对于data.frame中的每一列,查找列是唯一具有正值的行,r,dataframe,unique,R,Dataframe,Unique,我需要知道对于data.frame中的每一列,行的哪些元素是唯一的,然后在输出中打印行名 我的数据示例: id A B C s1 1 2 1 s2 1 0 0 s3 0 12 3 s4 0 1 0 s5 0 1 0 我想模仿一下: $A s2 $B s4,s5 $C NA 这意味着: A只有一个唯一的元素—s2 B有两个独特的元素——s4和s5 C没有任何独特的元素,所以它由NA填充 我试过了 apply(data, 2, func

我需要知道对于data.frame中的每一列,行的哪些元素是唯一的,然后在输出中打印行名

我的数据示例:

id  A   B   C
s1  1   2   1
s2  1   0   0
s3  0   12  3
s4  0   1   0
s5  0   1   0
我想模仿一下:

$A s2
$B s4,s5
$C NA 
这意味着:

A只有一个唯一的元素—s2

B有两个独特的元素——s4和s5

C没有任何独特的元素,所以它由NA填充

我试过了

apply(data, 2, function(x) unique(x))
但这不是我需要的


谢谢你的建议

这里是一个粗略的基础
R
解决方案:

helper <- function(x) {
  has_p <- x > 0
  if (sum(has_p) != 1) has_p[] <- FALSE 
  has_p
}
step1 <- as.data.frame(t(apply(df[-1], 1, helper)))

lapply(step1, function(x) df[[1]][x])

$A
[1] "s2"

$B
[1] "s4" "s5"

$C
character(0)
rows <- rowSums(df[-1] > 0) == 1
lapply(df[-1], function(x) df[["id"]][rows & x > 0])
数据

df <- structure(list(id = c("s1", "s2", "s3", "s4", "s5"), A = c(1L, 
1L, 0L, 0L, 0L), B = c(2L, 0L, 12L, 1L, 1L), C = c(1L, 0L, 3L, 
0L, 0L)), row.names = c(NA, -5L), class = "data.frame")

df@RonakShah是的,我的错,应该有S2,正如你所说,你是对的。逻辑对我来说似乎很清楚。如果列A是行
s2
中唯一具有正值的列,则返回该列的
s2
。您可以看到,
C
列没有正值,而其他列没有正值。@snoram是的,没错。因此,在n次p数据帧x中,您对值x[i,j](i=1,…,n和j=1,…,p)的定义在列j中是“唯一的”:所有值x[i,-j]都等于0,对吗?@AndrewK。酷,你的问题有点不寻常。我刚刚添加了一个更简单的解决方案。第二个选择应该是高效的one@akrun因为它没有额外的
if(all(!x))
,对吗?或者是否看到其他内容?是,并且没有其他步骤可转换为data.frame
df <- structure(list(id = c("s1", "s2", "s3", "s4", "s5"), A = c(1L, 
1L, 0L, 0L, 0L), B = c(2L, 0L, 12L, 1L, 1L), C = c(1L, 0L, 3L, 
0L, 0L)), row.names = c(NA, -5L), class = "data.frame")