質問
私は
のような文字列を持っていますc <- "Gary INMetro Chicago IL Metro"
.
私はやっています
d <- strsplit(c,"Metro")
.
を得るために
> d[1]
[[1]]
[1] "Gary IN" " Chicago IL "
.
しかし私は2つの異なる要素を必要とし、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
を除いた最初のステップIST 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"
.
3番目にデータフレームを構築する必要があります(完全なコード)
# 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");
所属していません StackOverflow