简体   繁体   English

For循环查找两个列表之间的匹配项(R)

[英]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.我有两个列表,每个列表都包含 a.txt 文件的路径。 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... 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:当然,我将加载文件并执行一些操作,而不是使用 print,但在此之前我收到此错误:

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非常感谢

In R , print is a functionR中, print是 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 ie doing the list[[1]] , list1[[2]] etc.除了上述问题之外,提取listnames(i)不起作用,因为它正在执行提取并返回一个vector ,即执行list[[1]]list1[[2]]等。

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是矢量化的,并且由于list元素的矢量长度为 1,

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

should work or use Map应该工作或使用Map

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM