R: Removing Space + Separator

I am new to R. Therefore, I have this vector containing the following:

> head(sampleVector)

[1] "| txt01 |   100 |         200 |       123.456 |           0.12345 |"
[2] "| txt02 |   300 |         400 |       789.012 |           0.06789 |"

I want to extract rows and break them into separate parts, with the data value apiece. I want to get a list resultListthat will eventually print the following:

> head(resultList)`

[[1]]`  
[1] ""   "txt01"    "100"       "200"     "123.456"        "0.12345" 

[[2]]`  
[1] ""   "txt02"    "300"       "400"     "789.012"        "0.06789"

I am struggling with a note strsplit(), and I tried and got the following code:

resultList  <- strsplit(sampleVector,"\\s+[|] | [|]\\s+ | [\\s+]")`          
#would give me the following output`

# [[1]]`    
# [1] "| txt01"    "100"       "200"     "123.456"        "0.12345 |" 

Anyway, can I get the output of one call strsplit? I assume that my notation to distinguish separator + space is incorrect. Any help on this would be good.

+4
source share
3 answers

Another parameter strsplitthat I almost missed:

strsplit(test,"[| ]+")
#[[1]]
#[1] ""        "txt01"   "100"     "200"     "123.456" "0.12345"
# 
#[[2]]
#[1] ""        "txt02"   "300"     "400"     "789.012" "0.06789"

... , regmatches - :

regmatches(test,gregexpr("[^| ]+",test))
#[[1]]
#[1] "txt01"   "100"     "200"     "123.456" "0.12345"
#
#[[2]]
#[1] "txt02"   "300"     "400"     "789.012" "0.06789"

:

[| ]+ - + pipe |
[^| ]+ - + , ^ pipe |
gregexpr .
regmatches test, gregexpr

+4

. | gsub. strsplit ( ). , .

strsplit(gsub("|", "", sampleVector, fixed=TRUE), "\\s+")
# [[1]]
# [1] ""        "txt01"   "100"     "200"     "123.456" "0.12345"
#
# [[2]]
# [1] ""        "txt02"   "300"     "400"     "789.012" "0.06789"

, scan, , , .

lapply(sampleVector, function(y) {
    s <- scan(text = y, what = character(), sep = "|", quiet = TRUE)
    (g <- gsub("\\s+", "", s))[-length(g)]
})
# [[1]]
# [1] ""        "txt01"   "100"     "200"     "123.456" "0.12345"
#
# [[2]]
# [1] ""        "txt02"   "300"     "400"     "789.012" "0.06789"
+4

Maybe try strsplit and gsub first:

sapply(strsplit(xx, '\\|'), function (x) gsub("^\\s+|\\s+$", "", x))
     [,1]     
[1,] ""       
[2,] "txt01"  
[3,] "100"    
[4,] "200"    
[5,] "123.456"
[6,] "0.12345"
0
source

All Articles