cea
cea

Reputation: 73

For-loop and coordinate duplicates in R

I would like to detect duplicate coordinates in a series:

n <- 0
for(ii in 1:11){
  for(jj in 1:11){
w <- ii
x <- jj
y <- ii
z <- jj
coord1 <- c(w, x)
coord2 <- c(y, z)
list_coord <- list(coord1, coord2)
if(sum(duplicated(list_coord)) > 0) n <- n+1
print(n)
}}

This works.

However, as soon as I fix one of the coordinates, R returns only zeros although there should be at least one n = 1:

n <- 0
for(ii in 1:11){
  for(jj in 1:11){
    w <- ii
    x <- jj
    y <- 4
    z <- 7
    coord1 <- c(w, x)
    coord2 <- c(y, z)
    list_coord <- list(coord1, coord2)
    if(sum(duplicated(list_coord)) > 0) n <- n+1
    print(n)
  }}

Why? Thanks for your help!

Upvotes: 2

Views: 174

Answers (1)

akrun
akrun

Reputation: 887108

The duplicated statement can be done on rbinding the 'coord1', 'coord2'

n <- 0
for(ii in 1:11){
  for(jj in 1:11){
    w <- ii
    x <- jj
    y <- 4
    z <- 7
    coord1 <- c(w, x)
    coord2 <- c(y, z)
    new_coord <- rbind(coord1, coord2)   
    if(sum(duplicated(new_coord)) > 0) n <- n+1
    #or
    #if(anyDuplicated(new_coord) > 0) n <- n+1

    print(n)
  }}

n
#[1] 1

Upvotes: 1

Related Questions