Alan Monziani
Alan Monziani

Reputation: 65

For loop to find matches between two lists (R)

it is a very trivial question, I checked the parentheses several times but I cannot notice anything wrong. I have two lists, each one having as factors the path to a .txt file. The two lists have the same names, and for each element in the first, I want to find the corresponding one in the second.

The lists look like this:

DEGs <- list(element1="path",
             element2="path",
             element3="path",
             element3="path",

etc...

And my code is this one:

for (i in list1) {
  for (k in list2) {
    if (names(i) == names(k)) {
      print paste0(i, " = ", k)
    }
  }
}

of course instead of using print I will load the files and doing some operations, but before that I am getting this error:

Error: unexpected symbol in:
"    if (names(i) == names(k)) {
      print paste0"
>     }
Error: unexpected '}' in "    }"
>   }
Error: unexpected '}' in "  }"
> }
Error: unexpected '}' in "}"
>

Does anyone know the problem? Pretty sure it is quite trivial. Many thanks

Upvotes: 1

Views: 288

Answers (1)

akrun
akrun

Reputation: 887223

In R, print is a function

for (i in list1) {
  for (k in list2) {
    if (names(i) == names(k)) {
      print(paste0(i, " = ", k))
    }
  }

In addition to the above issue, the names(i) from the extracted list wouldn't work because it is doing the extraction and returning a vector i.e. doing the list[[1]], list1[[2]] etc.

list1 <- list(element1 = 'a', element2 = 'b')
list2 <- list(element1 = 'c', element2 = 'd')

for(i in list1) print(i)
#[1] "a"
#[1] "b"

Instead this can be looped over the names

for(nm1 in names(list1)) {
   for(nm2 in names(list2)) {
       if(nm1 == nm2){ print(paste0(list1[[nm1]], " = ", list2[[nm2]]))
    }
     }
    }

Also, paste is vectorized and as the list elements have vectors of length 1,

paste(list1, list2, sep=" = ")

should work or use Map

unlist(Map(paste, list1, list2,  MoreArgs = list(sep = " = ")))

Upvotes: 3

Related Questions