library(stringr)
dt <- readLines("input.txt")
Warning in readLines("input.txt"): incomplete final line found on 'input.txt'
str_count(dt, "\\(") - str_count(dt, "\\)")
[1] 138
dt <- data.frame("paren" = t(str_split_fixed(dt, "", nchar(dt)))) dt$val <- ifelse(dt$paren == "(", 1, -1) which(cumsum(dt$val) == -1)[1]
[1] 1771