我有一个像

的字符串
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
.

其他提示

第一步是不允许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(帧,“test.frm”);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top