访问lapply中的行号

时间:2019-02-03 12:49:09

标签: r lapply

我想在lapply-iteration中访问当前行号:

lapply(dplyr::starwars$name[1:3], function(x){
  lapply(dplyr::starwars$name[2:4], function(y){
    paste(x,'&',y)
  })
})

在第二个lapply语句中,我需要访问当前第一个语句的以下条目,因此而不是此输出

x[1] - y[2]     Luke Skywalker & C-3PO
x[1] - y[3]     Luke Skywalker & R2-D2
x[1] - y[4]     Luke Skywalker & Darth Vader

x[2] - y[2]     C-3PO & C-3PO
x[2] - y[3]     C-3PO & R2-D2
x[2] - y[4]     C-3PO & Darth Vader

x[3] - y[2]     R2-D2 & C-3PO
x[3] - y[3]     R2-D2 & R2-D2
x[3] - y[4]     R2-D2 & Darth Vader

我希望获得此输出,以避免两次获得同一行

x[1] - y[2]     Luke Skywalker & C-3PO
x[1] - y[3]     Luke Skywalker & R2-D2
x[1] - y[4]     Luke Skywalker & Darth Vader

x[2] - y[3]     C-3PO & R2-D2
x[2] - y[4]     C-3PO & Darth Vader

x[3] - y[4]     R2-D2 & Darth Vader

是否可以找回当前行号(第一个lapply)并将其放入第二个lapply?

3 个答案:

答案 0 :(得分:1)

另一种方法呢?

combn(starwars$name[1:4], 2, paste, collapse = " & ")

[1] "Luke Skywalker & C-3PO"       "Luke Skywalker & R2-D2"       "Luke Skywalker & Darth Vader" "C-3PO & R2-D2"                "C-3PO & Darth Vader"         
[6] "R2-D2 & Darth Vader"     

答案 1 :(得分:1)

一种方法是在索引上使用lapply,但要引用函数内部的数据

lapply(1:3, function(x){
    lapply((x+1):4, function(y){
        paste(dplyr::starwars$name[x],'&',dplyr::starwars$name[y])
    })
})

答案 2 :(得分:0)

List<UserPrincipal> searchPrinciples = new List<UserPrincipal>();
searchPrinciples.Add(new UserPrincipal(context) { DisplayName="*Holonka*"});
searchPrinciples.Add(new UserPrincipal(context) { SamAccountName = "*Holonka*" });
searchPrinciples.Add(new UserPrincipal(context) { MiddleName = "*Holonka*" });
searchPrinciples.Add(new UserPrincipal(context) { GivenName = "*Holonka*" });
List<Principal> results = new List<Principal>();
foreach (var item in searchPrinciples)
{
    var searcher = new PrincipalSearcher(item);
    // Results may contains duplicate values because of separate searchers can handle the same user
    results.AddRange(searcher.FindAll());
}