简体   繁体   English

如何检查名称列表并使用所选元素?

[英]How check name list and use selected element?

I have two lists with different variables and their values. 我有两个列表,包含不同的变量及其值。 How can I check if the list name is correct in the conditional statement and then use selected element of list in the further part of the algorithm? 如何在条件语句中检查列表名称是否正确,然后在算法的其他部分使用列表中的所选元素?

sample_list1 <- list(
    varA = 11,
    varB = 22,
    varC = 33)
sample_list2 <- list(
    varE = 44,
    varF = 55,
    varG = 66)
sample_fun <- function(name_list) {
    if (name_list == sample_list1) {
        print(name_list)
    }
    else if (name_list == sample_list2) {
        print(name_list)
    }
    else stop ("Incorrect list name.")
}
sample_fun(sample_list1$varA) # It works
sample_fun(sample_list1$varB) # It doesn't work
sample_fun(sample_list2$varE) # It works
sample_fun(sample_list2$varF) # It doesn't work

If I've understood your question correctly you want your function to tell you if a given name is contained in either your list 1 or your list 2, or neither. 如果我已正确理解您的问题,您希望您的函数告诉您列表1或列表2中是否包含给定名称,或者两者都不包含。

I've written some code (and tested) so this should do the trick: 我写了一些代码(并经过测试),所以这应该可以解决问题:

sample_list1 <- list(
  varA = 11,
  varB = 22,
  varC = 33)

sample_list2 <- list(
  varE = 44,
  varF = 55,
  varG = 66)

sample_fun <- function(name_list) {
  # Check if the selection is in list1 or list2 
  if (name_list %in% sample_list1) {
    print ("Belongs to list 1") 
  }
  else if (name_list %in% sample_list2) {
    print("Belongs to list 2") 
  }
  else stop ("Incorrect list name.")
}

sample_fun(sample_list1$varA) # Belongs to list 1
sample_fun(sample_list1$varB) # Belongs to list 1
sample_fun(sample_list2$varE) # Belongs to list 2
sample_fun(sample_list2$varF) # Belongs to list 2

Although I'm a little confused by your conditional statements. 虽然我对你的条件陈述有点困惑。 You check for 2 different possibilities yet output the same result ( print(name_list) ). 您检查2种不同的可能性,但输出相同的结果( print(name_list) )。 How would you determine which condition was satisfied? 您如何确定满足哪种条件?

I made some minor adjustments to your code. 我对你的代码做了一些小的调整。

Just a try from me: 试试看我:

sample_list1 <- list(
  varA = 11,
  varB = 22,
  varC = 33)
sample_list2 <- list(
  varE = 44,
  varF = 55,
  varG = 66)

sample_fun <- function(name_list) {
  if (name_list == sample_list1$varA || name_list == sample_list1$varB || name_list == sample_list1$varC) {
    print("list 1")
  } else {
    print("list 2")
  }
}

sample_fun(sample_list1$varA) # "list 1"
sample_fun(sample_list1$varB) # "list 1"
sample_fun(sample_list2$varE) # "list 2"
sample_fun(sample_list2$varF) # "list 2"

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

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