【发布时间】:2017-04-19 02:42:56
【问题描述】:
我试图在 R 中将以下字符串分割为 3 个单独的列(国家、城市、计数)
Country City Count
Japan Tokyo 361
数据:
"country=Japan&city=Tokyo","361"
"country=Spain&city=Barcelona","359"
"country=United Kingdom&city=London","333"
"country=Japan&city=Fukuoka","259"
"country=United States of America&city=New York City","223"
我试过了:
library(data.table)
library(stringr)
df <- read.table(file.choose(), header = FALSE, sep = ",", colClasses = c('character', 'character'), na.strings = 'null')
df.1 <- data.table(str = as.character(df$V1))
df.2 <- df.1[grepl("country=.+&city=\\w+", str),
country := str_extract(str,"(?<=country=)(.+)"),
city := str_extract(str, "(?<=city=)(.+)")]
但是,虽然我想查看城市格式,但国家列将返回如下:
Japan&city=Tokyo
我想去掉 &city=Tokyo 位来制作漂亮的格式。
然后,我将 df 和 df.2 合并在一起,以便对齐数值。但是,我认为必须有更聪明的方法来做到这一点。
请分享你的知识。感谢您的帮助。
【问题讨论】: