r - 如何在r中的第n个字符之后拆分字符串
问题描述
我正在处理以下数据:
District <- c("AR01", "AZ03", "AZ05", "AZ08", "CA01", "CA05", "CA11", "CA16", "CA18", "CA21")
我想在第二个字符之后拆分字符串并将它们分成两列。
使数据看起来像这样:
state district
AR 01
AZ 03
AZ 05
AZ 08
CA 01
CA 05
CA 11
CA 16
CA 18
CA 21
有没有简单的代码来完成这项工作?非常感谢你的帮助
解决方案
substr
如果您总是想按第二个字符分割,则可以使用。
District <- c("AR01", "AZ03", "AZ05", "AZ08", "CA01", "CA05", "CA11", "CA16", "CA18", "CA21")
#split district starting at the first and ending at the second
state <- substr(District,1,2)
#split district starting at the 3rd and ending at the 4th
district <- substr(District,3,4)
#put in data frame if needed.
st_dt <- data.frame(state = state, district = district, stringsAsFactors = FALSE)
推荐阅读
- gradle - 从 gradle 中的发布中排除一两个子项目
- c - openSSL 读/写线程安全
- javascript - 访问 url 中的路由时如何修复 404 未找到。(SPA反应)
- html - 从 Angular 模板获取字符串而不是预期数字并输入本机元素的值
- rpm - 一个支持多种架构的 SPEC 文件
- c# - 有没有办法使用反射获取继承的泛型类的类型?
- android - 建议更改 build.gradle 文件后,背景可绘制对象导致膨胀异常
- tensorflow - TensorFlow 在执行推理时如何分配 GPU 内存?
- google-sheets - 从 Google 表格数据透视表中删除零行
- java - Spring Tool Suite 4 中的“找不到 java.lang.Object 的类文件”