首页 > 解决方案 > 如何在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

有没有简单的代码来完成这项工作?非常感谢你的帮助

标签: rstringsplitdata-management

解决方案


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)

推荐阅读