使用 tidyr 和 regex 创建两列
Using tidyr and regex to create two columns
我想将一列包含代码和地名的数据分成两列。我尝试使用 tidyr
的单独命令,但是 运行 在使用正则表达式时遇到了一些困难(我以前没有使用过它们并且无法弄清楚我做了什么 wrong/how 正则表达式真的作品)。
数据在格式方面非常一致。大多数观察以代码开头,然后是位置。偶尔会有一个观察只是一个位置(没有代码)。这是数据示例:
df <- read.table(text = c("
obs name
1 01-220 location 1
2 05-23 town 3
3 District 2"), header = T)
我使用以下代码:
df <- df %>% separate(name, into = c("location_code", "location_name"), sep = "([0-9] [A-z])")
导致(注意 location_code 的最后一个数字和 location_name 的第一个字母丢失):
obs location_code location_name
1 01-22 ocation 1
2 05-2 own 3
3 District 2 NA
我想要的输出是:
# obs location_code location_name
# 1 01-220 location 1
# 2 05-23 town 3
# 3 NA District 2
提前致谢!
我们可以使用正则表达式查找来指定 sep
。
separate(df, name, into = c("location_code", "location_time"),
"(?<=([0-9] )|\b)(?=[A-Za-z])")
# obs location_code location_time
#1 1 01-220 location 1
#2 2 05-23 town 3
#3 3 District 2
或 extract
extract(df, name, into = c("location_code", "location_time"), "([0-9-]*)\s*(.*)")
# obs location_code location_time
#1 1 01-220 location 1
#2 2 05-23 town 3
#3 3 District 2
数据
df <- structure(list(obs = 1:3, name = c("01-220 location 1", "05-23 town 3",
"District 2")), .Names = c("obs", "name"), class = "data.frame", row.names = c(NA,
-3L))
我想将一列包含代码和地名的数据分成两列。我尝试使用 tidyr
的单独命令,但是 运行 在使用正则表达式时遇到了一些困难(我以前没有使用过它们并且无法弄清楚我做了什么 wrong/how 正则表达式真的作品)。
数据在格式方面非常一致。大多数观察以代码开头,然后是位置。偶尔会有一个观察只是一个位置(没有代码)。这是数据示例:
df <- read.table(text = c("
obs name
1 01-220 location 1
2 05-23 town 3
3 District 2"), header = T)
我使用以下代码:
df <- df %>% separate(name, into = c("location_code", "location_name"), sep = "([0-9] [A-z])")
导致(注意 location_code 的最后一个数字和 location_name 的第一个字母丢失):
obs location_code location_name
1 01-22 ocation 1
2 05-2 own 3
3 District 2 NA
我想要的输出是:
# obs location_code location_name
# 1 01-220 location 1
# 2 05-23 town 3
# 3 NA District 2
提前致谢!
我们可以使用正则表达式查找来指定 sep
。
separate(df, name, into = c("location_code", "location_time"),
"(?<=([0-9] )|\b)(?=[A-Za-z])")
# obs location_code location_time
#1 1 01-220 location 1
#2 2 05-23 town 3
#3 3 District 2
或 extract
extract(df, name, into = c("location_code", "location_time"), "([0-9-]*)\s*(.*)")
# obs location_code location_time
#1 1 01-220 location 1
#2 2 05-23 town 3
#3 3 District 2
数据
df <- structure(list(obs = 1:3, name = c("01-220 location 1", "05-23 town 3",
"District 2")), .Names = c("obs", "name"), class = "data.frame", row.names = c(NA,
-3L))