tomatoiscoding
10/13/2016 - 2:27 PM

some tricks for regular expression in R

some tricks for regular expression in R

con <- file('path/file.txt','r')
test <- readLines(con)[[1]]
text <- c("1", "2", "3")
paste(text, collapse = '') # "123"
text <- as.numeric(as.matrix(text)) # [1] 1 2 3


t <- c("1 2 3")
gsub("\\s", "", t) # "123"
gsub("[[:space:]]", "", t) # "123"
# read character with scan()
scan(file = 'path/to/file', what = "character")
# convert charactor vector to a matrix
a <- rep(NA, 2) # generate a vector
a[1] <- '1, 2, 3, 4'
a[2] <- '5, 6, 7, 8'
a <- gsub('\\s', '', a)
b <- matrix(NA, length(a), 4)
for(i in 1:length(a)) {
  b[i, ] <- as.numeric(as.matrix(strsplit(a[i], ',')[[1]]))
}