R-character coefficient for a number vector

I read in the csv file with "3:29" in one of the fields (without quotes). This is becoming a factor. How can I convert this to a number vector, for example. with (3:29)? I tried as.vector (), but this gives the string vector "3,4,5,6 ... 29" (with quotes, another character class).

The EDIT answer should be applicable to a more general form, for example, a column may contain 3: 6,7,9: 11, which must be converted to the equivalent of c (3: 6,7,9: 11).).

+3
source share
2 answers

You can do:

> eval(parse(text='3:29'))
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
[26] 28 29
+10
source

Divide the string by :and convert to a vector of numeric numbers and call the call seq()manually:

> vars <- as.numeric(strsplit("3:29", ":")[[1]])
> seq(from = vars[1], to = vars[2], by = 1)
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
[26] 28 29

, R, `:()`:

> do.call(`:`, as.list(as.numeric(strsplit("3:29", ":")[[1]])))
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
[26] 28 29

[ Q]

:

> require(fortunes)
> fortune(106)

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

, parse():

unlist(lapply(strsplit(strsplit(txt, ",")[[1]], ":"),
       function(x) {
           x <- as.numeric(x)
           if(length(x) == 2) {
               seq(x[1], x[2], by = 1) ## `:`(x[1], x[2])
           } else { 
               x[1]
           }
       }))

:

[1]  3  4  5  6  7  9 10 11

... , , parse() ; -)

+2

Source: https://habr.com/ru/post/1787717/


All Articles