Home > Mobile >  Split Character String at Underscore Using scan() Function in R - strsplit() vs. scan() Comparison
Split Character String at Underscore Using scan() Function in R - strsplit() vs. scan() Comparison

Time:01-06

I've noticed that the functions strsplit() and scan() handle underscores differently, and I'm wondering why this is the case.

Please consider the following example code:

x1 <- "string split"

strsplit(x1, " ")[[1]]
# [1] "string" "split" 

scan(text = x1, what = " ")
# [1] "string" "split" 

The outputs of strsplit and scan are the same when using " " as a separator.

However, when I use "_" as a separator, the output is different:

x2 <- "string_split"

strsplit(x2, "_")[[1]]
# [1] "string" "split" 

scan(text = x2, what = "_")
# [1] "string_split"

Why is the output of strsplit and scan different when using underscores as a separator?

CodePudding user response:

the argument what is not the separator but rather the data type. IN your case, you have character:

scan(text=x2, what = character(), sep='_', quiet = TRUE)
[1] "string" "split" 
  •  Tags:  
  • Related