Convert comma separated string to integer in R

前端 未结 2 1870
长情又很酷
长情又很酷 2020-12-21 12:29

I have a line in following format

IP1: IP2: 0.1,0.5,0.9

I split this line using following command:

myVector <- (strsplit(oneLine, \":\"))

相关标签:
2条回答
  • 2020-12-21 12:50

    You can use gregexpr and regmatchesto extract the numbers:

    as.numeric(unlist(regmatches(oneLine, gregexpr("-?\\d+\\.\\d+", oneLine))))
    # [1] 0.1 0.5 0.9
    
    0 讨论(0)
  • 2020-12-21 12:55

    Here'a an approach using scan:

    oneLine <- "IP1: IP2: 0.1,0.5,0.9"
    myVector <- strsplit(oneLine, ":")
    listofPValues <- myVector[[1]][[3]]
    listofPValues
    # [1] " 0.1,0.5,0.9"
    scan(text = listofPValues, sep = ",")
    # Read 3 items
    # [1] 0.1 0.5 0.9
    

    And one using strsplit:

    as.numeric(unlist(strsplit(listofPValues, ",")))
    # [1] 0.1 0.5 0.9
    
    0 讨论(0)
提交回复
热议问题