Question

I have a string like

c <- "Gary INMetro Chicago IL Metro"

I am doing

d <- strsplit(c,"Metro")

to get

> d[1]
[[1]]
[1] "Gary IN" " Chicago IL "

But I want two different elements and want to write to the csv file as

 City,State
 Gary,IN
 Chicago,IL

How to do that? Any help is appreciated.

Was it helpful?

Solution

Try this:

read.table(text=gsub('Metro', '\n', c), col.names=c('City', 'State'))
#      City State
# 1    Gary    IN
# 2 Chicago    IL

OTHER TIPS

First step ist to unlist the strsplit

  d <- unlist(strsplit(c,"Metro"))

so you get single line vectors.

  [1] "Gary IN"      " Chicago IL "

Second you need to iterate over the vectors and trim your strings.

   trim <- function (x) gsub("^\\s+|\\s+$", "", x)
   for(i in 1:length(d)) { print(trim(d[i])) }

   [1] "Gary IN"
   [1] "Chicago IL"

Third you have to build a dataframe (complete code)

# 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");

Result

     City State
1    Gary    IN
2 Chicago    IL

At least store it

write.csv(frame,"test.frm");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top