问题
I have tried searching, but cannot find the exact thing I am looking to do. My apologies if I have overlooked it. I am trying to take a long vector of character strings, all with the same general structure, and place them into a data.frame. The structure is as follows:
[1] "rank, team, record"
[2] "1 Team 22-4"
[3] "2 Long Team Name 20-6"
My initial thought was to use gsub and a regex expression to place /" around the team names (ex. /"Long Team Name/") then use read.table to import, but I am running into difficulty coming up with the regex expression to do this. This would allow me to read in the string as tab delimited string, correct? If there is an easier suggestion, I am all ears.
Thanks! Brian
回答1:
I think this is what you want?
library(stringi)
x = c("rank, team, record", "1 Team 22-4", "2 Long Team Name 20-6")
res = stri_replace_first_fixed(x, " ", "|")
res = stri_replace_last_fixed(res, " ", "|")
res = stri_split_fixed(res, pattern = "|", simplify = T)
# [,1] [,2] [,3]
# [1,] "rank," "team," "record"
# [2,] "1" "Team" "22-4"
# [3,] "2" "Long Team Name" "20-6"
The result is a matrix, but you could wrap it in as.data.frame
.
来源:https://stackoverflow.com/questions/42684224/using-gsub-regex-to-place-quotes-around-names-inside-string