首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对长度大于1的列表组件使用“a”

对长度大于1的列表组件使用“a”
EN

Stack Overflow用户
提问于 2015-11-22 13:07:10
回答 1查看 141关注 0票数 1

我有一个类似于以下内容的清单:

代码语言:javascript
复制
> x <- list(
    j = "first",
    k = "second",
    l = "third",
    m = c("first", "second"),
    n = c("first", "second", "third"),
    o = c("first", "third"),
    p = c("second", "third"),
    q = "first",
    r = "third")

我需要根据字符串组件的值创建它们的索引。对于包含单个字符串元素的组件,我可以很容易地使用which完成此操作:

代码语言:javascript
复制
> which(x == "third")
l r
3 9

甚至对于包含单个字符串元素的多个组件:

代码语言:javascript
复制
> which(x == "first" | x == "second" | x == "third")
j k l q r
1 2 3 8 9

返回的值显示列表中组件的数量及其名称。但是,有时我需要获得包含多个元素(如m (c("first", "second"))或n (c("first", "second", "third")) )的字符向量的组件索引。也就是说,组件中字符向量的长度将大于1。我认为以下内容可以工作:

代码语言:javascript
复制
which(x == c("first", "second"))

我错了,结果是:

代码语言:javascript
复制
j k
1 2
Warning message:
In x == c("first", "second") :
  longer object length is not a multiple of shorter object length

当我尝试一个以上的条件时,情况也是一样的:

代码语言:javascript
复制
> which(x == "first" | x == c("first", "second"))
j k q
1 2 8
Warning message:
In x == c("first", "second") :
  longer object length is not a multiple of shorter object length

which(x == c("first", "second"))的期望输出是:

代码语言:javascript
复制
m
4

which(x == "first" | x == c("first", "second"))的期望输出是:

代码语言:javascript
复制
j m q
1 4 8

这是怎么做到的?不用用which,你.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-22 13:57:53

通过使用"list" == "character","list“被转换为”as.character(x)“,我认为这是不需要的。您可以使用match比较“list”的相应元素:

代码语言:javascript
复制
ff = function(x, table) which(setNames(table %in% x, names(table)))
ff(list("third"), x)
#l r 
#3 9 
ff(list("first", "second", "third"), x) # your "|"
#j k l q r 
#1 2 3 8 9 
ff(list(c("first", "second")), x)
#m 
#4 
ff(list("first", c("first", "second")), x) # your "|"
#j m q 
#1 4 8 
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33855104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档