r - 从R中的字符串中提取多个数值
问题描述
我有一个数据集,我想只从以下字符串中提取数值:
{ "What are the last three digits of your zip code?": "043", "What are the last three digits of your phone number?": "681"}
具体来说,我想将其提取为两个单独的列(043 和 681)。有没有办法用字符串中的这些符号来做到这一点?
解决方案
我们可以用str_extract_all
library(stringr)
str_extract_all(str1, "\\d+")[[1]]
#[1] "043" "681"
如果有多个元素,我们可以这样做
library(dplyr)
library(tidyr)
tibble(col1 = str2) %>%
mutate(col1 = str_extract_all(str2, "\\d+")) %>%
unnest_wider(c(col1)) %>%
set_names(str_c('col', seq_along(.)))
-输出
# A tibble: 2 x 2
# col1 col2
# <chr> <chr>
#1 043 681
#2 313 681
数据
str1 <- "{ \"What are the last three digits of your zip code?\": \"043\", \"What are the last three digits of your phone number?\": \"681\"}"
str2 <- c('{ "What are the last three digits of your zip code?": "043", "What are the last three digits of your phone number?": "681"}', '{ "What are the last three digits of your zip code?": "313", "What are the last three digits of your phone number?": "681"}')
推荐阅读
- terraform - 使用 for_each 在 terraform 函数中使用列表/元组
- java - 删除特定对象后,数组列表中的对象被遗漏
- authentication - Google 如何跨多个平台/域与登录用户进行交流?
- java - kotlin/java 用正则表达式匹配字符串中的数字
- spring-security - spring security 自定义登录 - 如何使用 html 表单操作获取响应?
- c# - 我在 >NET Web API 中实现 MediatR 时遇到问题。我不知道发生了什么
- sql - BigQuery 时间戳显示 .9999
- eclipse - Eclipse:新建Java类向导:为什么不总是填入包?
- windows - 为什么批处理文件命令行参数在控制台中消失?
- puppeteer - Puppeteer 机器人检测