'which' 语句中未知数量的条件

Unknown Number of Conditions in 'which' Statement

我有一个 selectInput 允许用户 select 多个国家。我想获取那些国家并从中创建数据。

像那样:

data_multicountry<-data[which(data$Country==input$countryInput[1] |
                              data$Country==input$countryInput[2] |
                              data$Country==input$countryInput[3]),]

不过条件可多可少。例如;

data_multicountry<-data[which(data$Country==input$countryInput[1] |
                              data$Country==input$countryInput[2] |
                              data$Country==input$countryInput[3] |
                              data$Country==input$countryInput[4] ),]

我可以获得 selected 国家列表的长度。 如何以编程方式添加 OR 语句?

使用 data.table 这实际上是一件非常简单的事情。首先,您不需要在条件中指定数据集的名称。 data.table 已经知道你正在使用 this table,所以只需要变量名。其次,您可以创建另一个变量或列表来存储您的用户 select 编辑的所有国家,然后将该变量用作您的 select 的条件。请参考下面的例子。

> DT = data.table(var1=c('a', 'b', 'c', 'd'), var2=c(1,2,3,4))
> DT
   var1 var2
1:    a    1
2:    b    2
3:    c    3
4:    d    4
> lst=list('a','d')
> DT[var1 %in% lst,]
   var1 var2
1:    a    1
2:    d    4

Heredata.table 上的一个很好的常见问题解答。