我有一个矢量:
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
答案 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