【问题标题】:How to Split a String into two different elements in R?如何在R中将字符串拆分为两个不同的元素?
【发布时间】:2014-02-25 21:31:58
【问题描述】:

我有一个类似

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


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 这真是太聪明了。我喜欢它。
    【解决方案2】:

    第一步是取消列出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(frame,"test.frm");

    【讨论】:

    • 那么如何区分Gary和IN呢?有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多