在二进制向量中找到前面带有0的1

时间:2017-04-06 07:43:40

标签: r vector

假设我有一个由10组成的二进制数字向量。我想在数字向量中找到1之前的05, 9, 12。所以我想得到以下向量的位置x <- c(1,1,0,0,1,1,1,0,1,0,0,1)

which(x==0 & x[-1]==1, T)

我试过这种方式:

from selenium import webdriver
driver = webdriver.PhantomJS()
#Unicodeerror occur
driver.get(url)

Traceback (most recent call last):
  File "C:\Users\name\Desktop\test.py", line 12, in <module>
    driver = webdriver.PhantomJS()
  File "C:\Users\name\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py", line 58, in __init__
    desired_capabilities=desired_capabilities)
  File "C:\Users\name\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 98, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "C:\Users\name\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 185, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Users\name\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 247, in execute
    response = self.command_executor.execute(driver_command, params)
  File "C:\Users\name\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 464, in execute
    return self._request(command_info[0], url, body=data)
  File "C:\Users\name\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 537, in _request
    body = data.decode('utf-8').replace('\x00', '').strip()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 189: invalid start byte

但它得到的是0,然后是1,这是位置4,8和11。

5 个答案:

答案 0 :(得分:3)

which(x & c(FALSE, diff(x) == 1L))
#[1]  5  9 12

请注意,二进制向量的更合适的数据类型是logical

答案 1 :(得分:2)

我们可以从向量中删除最后一个观察和第一个观察,检查它是否分别等于0和1

which(x[-length(x)]==0 & x[-1]==1) +1
#[1]  5  9 12

答案 2 :(得分:2)

为什么不这样:

which(diff(x)==1)+1
#[1]  5  9 12

由于它是一个二元向量,只要diff前面有11评估就会给0

答案 3 :(得分:1)

另一种选择:

which(tail(x, -1) & !head(x, -1)) + 1
#[1]  5  9 12

答案 4 :(得分:0)

我们也可以从lag尝试dplyr

which(x == 1 & dplyr::lag(x, 1, 1) == 0)
# [1]  5  9 12