I have a string:
a = c("112 271 [X];313 179 [X];125 162;123 131 [X];124 107")
I want to first split it by semicolon ;
b = as.list(strsplit(a, ";")[[1]])
> b
[[1]]
[1] "112 271 [X]"
[[2]]
[1] "313 179 [X]"
[[3]]
[1] "125 162"
[[4]]
[1] "123 131 [X]"
[[5]]
[1] "124 107"
then I want to split b by space, and save the result as a 3-column data frame.
The result looks like:
A B C
1 112 271 [X]
2 313 179 [X]
3 125 162
4 123 131 [X]
5 124 107
I don’t know how to do it. Thanks for your help.
>Solution :
Replace semicolon with newline then fread with fill, and set the column names:
data.table::fread(gsub(";", "\n", a),
fill = TRUE,
col.names = LETTERS[1:3])
# A B C
# 1: 112 271 [X]
# 2: 313 179 [X]
# 3: 125 162
# 4: 123 131 [X]
# 5: 124 107