我有一個字符串像如何將字符串拆分爲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