Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a vector of strings over a character to return a matrix

Tags:

string

regex

r

I have

rownames(results.summary)
[1] "2 - 1" "3 - 1" "4 - 1"

What I want is to return a matrix of

2  1
3  1
4  1

The way Ive done it as:

for(i in 1:length(rownames(results.summary)){
  current.split <- unlist(strsplit(rownames(results.summary)[i], "-"))
  matrix.results$comparison.group[i] <- trim(current.split[1])
  matrix.results$control.group[i] <- trim(current.split[2])
}

The trim function basically removes any whitespace on either end.

I've been learning regex and was wondering if there's perhaps a more elegant vectorized solution?

like image 473
user1357015 Avatar asked Dec 05 '25 13:12

user1357015


2 Answers

No need to use strsplit, just read it using read.table:

 read.table(text=vec,sep='-',strip.white = TRUE) ## see @flodel comment
  V1 V2
1  2  1
2  3  1
3  4  1

where vec is :

vec <-  c("2 - 1", "3 - 1", "4 - 1")
like image 128
agstudy Avatar answered Dec 07 '25 05:12

agstudy


This should work:

vv <- c("2 - 1", "3 - 1", "4 - 1")
matrix(as.numeric(unlist(strsplit(vv, " - "))), ncol = 2, byrow = TRUE)
#      [,1] [,2]
# [1,]    2    1
# [2,]    3    1
# [3,]    4    1
like image 28
Kara Woo Avatar answered Dec 07 '25 05:12

Kara Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!