我有一个字符串像如何将字符串拆分为R中的两个不同元素?
c <- "Gary INMetro Chicago IL Metro"
我做
d <- strsplit(c,"Metro")
得到
> d[1]
[[1]]
[1] "Gary IN" " Chicago IL "
但我想两个不同的元素,并要写入csv文件作为
City,State
Gary,IN
Chicago,IL
如何做到这一点?任何帮助表示赞赏。
我有一个字符串像如何将字符串拆分为R中的两个不同元素?
c <- "Gary INMetro Chicago IL Metro"
我做
d <- strsplit(c,"Metro")
得到
> d[1]
[[1]]
[1] "Gary IN" " Chicago IL "
但我想两个不同的元素,并要写入csv文件作为
City,State
Gary,IN
Chicago,IL
如何做到这一点?任何帮助表示赞赏。
试试这个:
read.table(text=gsub('Metro', '\n', c), col.names=c('City', 'State'))
# City State
# 1 Gary IN
# 2 Chicago IL
第一步IST设为不公开的strsplit
d <- unlist(strsplit(c,"Metro"))
等你拿单行向量。
[1] "Gary IN" " Chicago IL "
其次你需要遍历向量并修剪你的字符串。
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
for(i in 1:length(d)) { print(trim(d[i])) }
[1] "Gary IN"
[1] "Chicago IL"
第三,你必须建立一个数据帧(完整代码)
# Function to trim the fields
trim <- function(x) { gsub("^\\s+|\\s+$", "", x) }
# Dataset
c <- "Gary INMetro Chicago IL Metro"
# Split text rows
d <- unlist(strsplit(c,"Metro"))
# Build an empty frame
frame <- data.frame()
# Split columns and collect the rows
for(i in (1:length(d))) {
# Split columns
r <- unlist(strsplit(trim(d[i])," "))
# Collect rows
frame[i,1] <- r[1];
frame[i,2] <- r[2];
}
# Set table names
names(frame) <- c("City","State");
结果
City State
1 Gary IN
2 Chicago IL
存储至少它
write.csv(帧,“测试。 FRM“);
如何分离加里和IN呢?任何想法? – user3188390
lookat strsplit ... – huckfinn
这真的很聪明。我喜欢。 – stanekam