1

I am working in R and am supposed to split the stdin inputs using space and newline characters. However, when I take the input as a string from stdin using the following code:

f <- file("stdin")
open(f)

sampleInput <- readLines(f)

with the following values in stdin:

1 2
3 4 4

print(sampleInput) returns the following output and I am not sure how to split it.

[1] "1 2"   "3 4 4"

Can someone suggest a way to split this input using space and newline characters (just like split() works in python) as follows?

[1] "1" "2" "3" "4" "4"
Naman Bansal
  • 191
  • 2
  • 13
  • 1
    You can try `sampleInput <- unlist(strsplit(readLines(f), " "), FALSE, FALSE)`. This further splits each string by `" "` and flattens the list into a vector. – ekoam Jan 11 '22 at 08:50
  • Just a little modification to accommodate next line characters `sampleInput <- readLines(f) sampleInput <- gsub(", "," ",toString(sampleInput)) sampleInput <- unlist(strsplit(sampleInput, " "), FALSE, FALSE)` – Naman Bansal Jan 11 '22 at 09:10

0 Answers0