[英]Get indexes from a vector with multiple elements based on a specific value
I have a vector: 我有一个向量:
lst <- c("2,1","7,10","11,0","7,0","10,0","1,1","1,0","4,0","4,1","0,1","6,0")
each element contains two numbers,separated by ",". 每个元素包含两个数字,以“,”分隔。 I would like to get indexes of elements containing "1".
我想获取包含“ 1”的元素的索引。 So the index list is expected:
因此,索引列表是预期的:
1, 6, 7, 9, 10
grep()
will work nicely for this. grep()
将为此很好地工作。 By default, it returns the indices of the matched pattern. 默认情况下,它返回匹配模式的索引。
grep("^1,|,1$", lst)
# [1] 1 6 7 9 10
The regular expression ^1,|,1$
looks to match a string that 正则表达式
^1,|,1$
看起来要匹配一个字符串
^1,
= starts with 1,
^1,
=以1,
开头 |
OR ,1$
= ends with ,1
,1$
=以,1
结尾 each element contains two numbers. 每个元素包含两个数字。 my answer is not ideal but I got what I need.
我的回答并不理想,但是我得到了我所需要的。
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))))
Depending on background and context of this task it might be prudent to turn this vector into a data.frame: 根据此任务的背景和上下文,可能需要谨慎地将此向量转换为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.