如何将字符串拆分为R中的两个不同元素?

时间:2021-06-16 21:46:12

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

但我想要两个不同的元素,并希望写入csv文件

 City,State
 Gary,IN
 Chicago,IL

How to do that? Any help is appreciated.

怎么做?任何帮助表示赞赏。

2 个解决方案

#1


4  

Try this:

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

#2


1  

First step ist to unlist the strsplit

第一步是取消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");

#1


4  

Try this:

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

#2


1  

First step ist to unlist the strsplit

第一步是取消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");