Split a string vector at whitespace

后端 未结 9 1931
独厮守ぢ
独厮守ぢ 2020-12-08 09:35

I have the following vector:

tmp3 <- c(\"1500 2\", \"1500 1\", \"1510 2\", \"1510 1\", \"1520 2\", \"1520 1\", \"1530 2\", 
\"1530 1\", \"1540 2\", \"1540         


        
相关标签:
9条回答
  • 2020-12-08 10:31
    substr(x = tmp3, start = 6, stop = 6)
    

    So long as your strings are always the same length, this should do the trick.

    (And, of course, you don't have to specify the argument names - substr(tmp3, 6, 6) works fine, too)

    0 讨论(0)
  • 2020-12-08 10:33

    Another option is scan(). To get the second value, we can use a logical subset.

    scan(text = tmp3)[c(FALSE, TRUE)]
    #  [1] 2 1 2 1 2 1 2 1 2 1
    
    0 讨论(0)
  • 2020-12-08 10:41

    An easier way to split 1 column into 2 columns via data.table

    require(data.table)  
    data_ex = data.table( a = paste( sample(1:3, size=10, replace=TRUE),"-separate", sep="" ))  
    data_ex[, number:=  unlist( strsplit(x=a, split="-") )[[1]], by=a]  
    data_ex[, word:= unlist( strsplit(x=a, split="-") )[[2]], by=a ]
    
    0 讨论(0)
提交回复
热议问题