比较R

时间:2016-06-08 18:53:46

标签: r list compare

我创建了两个列表,第一个名为list1,其中4个元素包含4位,第二个list2包含1个4位元素。我想比较列表,如果list1中的任何元素与list2中的唯一元素相同,那么我想从list1中删除该元素。我已经实现了以下代码,但没有得到正确的结果。

list1<-c()
n<-4
#Creating list1 with 4 vectors having 4 bits each
for(i in 1:5)
{
  rndno<-round(runif(1, 1, 2^n -1),0)
  bn<-bin(rndno)
  pad<-rep.int(0,n-length(bn))
  bn<-c(pad,bn)
  list1<-rbind(list1,bn)
}
list2<-c()
rndno<-round(runif(1, 1, 2^n -1),0)
bn<-bin(rndno)
pad<-rep.int(0,n-length(bn))
bn<-c(pad,bn)
list2<-rbind(list2,bn)
for(i in 1:nrow(k))
{
  if(list2[1,] == list2[i,])
  {
    print(i)
  }
}

请帮助。

1 个答案:

答案 0 :(得分:0)

问题是你没有在你的例子中定义bin函数,所以我们只能猜出你想要实现的目标。但我认为你想做这样的事情:

bin <- function(x) {
  i <- 0
  string <- numeric(32)
  while(x > 0) {
    string[32 - i] <- x %% 2
    x <- x %/% 2
    i <- i + 1 
  }
  first <- match(1, string)
  string[first:32] 
}

此函数将十进制数转换为二进制数。

将随机数生成器设置为给定值也很有用 为了使您的脚本可重现:

set.seed(1)

现在,这是您的代码,尽管它可能不是创建数据的最有效方式。另请注意,您已命名对象列表,但实际上,您在这里处理矩阵。

list1<-c()
n<-4
#Creating list1 with 4 vectors having 4 bits each
for(i in 1:5)
{
  rndno<-round(runif(1, 1, 2^n -1),0)
  bn<- bin(rndno)
  pad<-rep.int(0,n-length(bn))
  bn<-c(pad,bn)
  list1<-rbind(list1,bn)
}

# [,1] [,2] [,3] [,4]
# bn    0    1    0    1
# bn    0    1    1    0
# bn    1    0    0    1
# bn    1    1    1    0
# bn    0    1    0    0

list2<-c()

rndno<-round(runif(1, 1, 2^n -1),0)
bn<-bin(rndno)
pad<-rep.int(0,n-length(bn))
bn<-c(pad,bn)
list2<-rbind(list2,bn)

# [,1] [,2] [,3] [,4]
# bn    1    1    1    0

现在,为了从list2删除list1中指定的值,您将矩阵的行与目标向量进行比较,并且只选择没有完全匹配的行:

list1[apply(apply(list1, 1, function(x) x == list2), 2, function(x) any(x == FALSE)),]

# [,1] [,2] [,3] [,4]
# bn    0    1    0    1
# bn    0    1    1    0
# bn    1    0    0    1
# bn    0    1    0    0