从具有基于特定值的多个元素的向量中获取索引

时间:2016-10-27 18:19:01

标签: r regex

我有一个矢量:

lst <- c("2,1","7,10","11,0","7,0","10,0","1,1","1,0","4,0","4,1","0,1","6,0")

每个元素包含两个数字,用&#34;,&#34;分隔。我想得到包含&#34; 1&#34;的元素的索引。 所以索引列表是预期的:

1, 6, 7, 9, 10

3 个答案:

答案 0 :(得分:3)

grep()可以很好地解决这个问题。默认情况下,它返回匹配模式的索引。

grep("^1,|,1$", lst)
# [1]  1  6  7  9 10

正则表达式^1,|,1$看起来匹配

的字符串
  • ^1, =以1,
  • 开头
  • |
  • ,1$ =以,1
  • 结尾

答案 1 :(得分:0)

每个元素包含两个数字。我的回答并不理想,但我得到了我需要的东西。

m <- as.numeric(unlist(lapply(strsplit(as.character(lst), "\\,"),"[[",1)))
n <- as.numeric(unlist(lapply(strsplit(as.character(lst), "\\,"),"[[",2)))
sort(unique(c(which(m==1),which(n==1))))

答案 2 :(得分:0)

根据此任务的背景和上下文,将此向量转换为data.frame可能是明智的:

lst <- c("2,1","7,10","11,0","7,0","10,0","1,1","1,0","4,0","4,1","0,1","6,0")
DF <- read.table(text = do.call(paste, list(lst, collapse = "\n")), sep = ",")
which(DF$V1 == 1L | DF$V2 == 1L)
#[1]  1  6  7  9 10