繁体   English   中英

从R中的字符串中提取多个带引号的值

[英]Extracting Multiple Quoted Values from String in R

我正在尝试从字符串中提取多个带引号的值:

{  "What is your license plate number?": "FSD15a",  "What is the color of your car?": "Grey",  "What is the make AND model of your car?": "Hyundai Sonata",  "What are the last three digits of your zip code?": "043",  "What are the last three digits of your phone number?": "681"}

具体来说,我希望这些值中的每一个(例如,您的车牌号是多少?、FSD15a、您的汽车的品牌和型号是什么、现代索纳塔等)成为 df 中的新列,并且之前使用过以下代码仅提取数字:

df %>% mutate(col1 = str_extract_all(Custom.Fields, "\\d+")) %>%
unnest_wider(c(col1)) %>%
set_names(c(names(df), str_c('col', seq_along(.)[-1])))

我一生都无法弄清楚如何使用引用的值来做到这一点。 您能提供的任何帮助将不胜感激!

使用jsonlite更容易

library(jsonlite)
as.data.frame(fromJSON(Custom.Fields), check.names = FALSE)

-输出

What is your license plate number? What is the color of your car? What is the make AND model of your car?
1                             FSD15a                           Grey                          Hyundai Sonata
  What are the last three digits of your zip code? What are the last three digits of your phone number?
1                                              043                                                  681

如果有多个条目,请在}{之间拆分,然后通过循环应用fromJSON

do.call(rbind.data.frame, lapply(strsplit(Custom.Fields, 
   "(?<=\\})\\s+(?=\\{)", perl = TRUE)[[1]], fromJSON))
What.is.your.license.plate.number. What.is.the.color.of.your.car. What.is.the.make.AND.model.of.your.car.
1                                N/A                            N/A                                     N/A
2                             ABC123                          Blue                        Toyota Highlander
  What.are.the.last.three.digits.of.your.zip.code. What.are.the.last.three.digits.of.your.phone.number.
1                                            30127                                                  389
2                                              083                                                  313

数据

Custom.Fields <- '{  "What is your license plate number?": "FSD15a",  "What is the color of your car?": "Grey",  "What is the make AND model of your car?": "Hyundai Sonata",  "What are the last three digits of your zip code?": "043",  "What are the last three digits of your phone number?": "681"}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM