【问题标题】:Loop over each line and store each word in a line and make a data frame in R循环遍历每一行并将每个单词存储在一行中并在 R 中创建一个数据框
【发布时间】:2012-10-04 05:14:08
【问题描述】:

我有以下文件:

[1]/tI /tam /tCharlotte   
[2]/ti /tam /tcharlotte   
[3]/tYou /tare /tsmart  
[4]/tyou /tare /tsmart  

并且我希望输出数据框具有以下形式:

word      gloss  
I         i  
am        am      
Charlotte charlotte    
You       you    
are       are    
smart     smart    

是否可以为此编写代码?我需要按标签分隔文件吗?

【问题讨论】:

  • 是 [1], [2], ... 文件的一部分还是只是从 R 输出?
  • “/t”应该是制表符吗?在大多数语言中是 "\t" 。

标签: string r loops dataframe


【解决方案1】:

此解决方案类似于@csgillespie 的解决方案,但每次都在一个命令中完成(一旦读取数据)。

读取数据:

dat <- read.table(text = "/tI /tam /tCharlotte   
/ti /tam /tcharlotte   
/tYou /tare /tsmart  
/tyou /tare /tsmart", stringsAsFactors = FALSE)

创建数据框:

structure(
 as.data.frame(
  lapply(
   lapply(list(c(TRUE, FALSE), c(FALSE, TRUE)),
          function(y) lapply(strsplit(
                              apply(dat, 1, "paste", collapse = ""), "/t"),
                             function(x) x[nchar(x) > 0])[y]),
   unlist)),
 .Names = c("word", "gloss"))

【讨论】:

    【解决方案2】:

    你的问题并不完全清楚。例如,

    1. 您的文件中是否有数字 [1]、[2]、...?
    2. 偶数行是否只是奇数行的小写版本?

    忽略数字并假设奇数行和偶数行不同,一种解决方案是:

    ##Read in the data. 
    tmp = read.table(textConnection("/tI /tam /tCharlotte   
    /ti /tam /tcharlotte   
    /tYou /tare /tsmart  
    /tyou /tare /tsmart"), sep="\n", stringsAsFactors=FALSE)
    
    ##Take the odd rows
    ##gsub: remove white space
    ##strsplit: split the string on "\t"
    ##unlist: go from a list to a vector
    c1 = unlist(
        strsplit(
            gsub(" ", "", tmp[seq(1,nrow(tmp), 2),]), "/t"))
    
    ##Ditto the even rows
    c2 = unlist(
        strsplit(
            gsub(" ", "", tmp[seq(2,nrow(tmp), 2),]), "/t"))
    

    这为我们提供了两个可以放入数据框中的向量:

    dd = data.frame(c1 = c1, c2 = c2)
    

    我想你不想要空行,所以只需删除它们:

    dd[apply(dd, 1, function(i) sum(nchar(i))>0),]
    

    【讨论】:

    • 嗨!感谢您的代码!我的实际文件比这更复杂。因此,在奇数行中,有来自一种语言(不是英语)的单词,在偶数行中,每个单词都有英文翻译。文件中总共有 1200 行。我想制作一个数据框,其中每个单词及其英文翻译都配对在一起。
    • 如果线路是配对的,那么重复 rbind( t(mydata[1:2,]), t(mydata[2:3,]) 将为您完成。显然,您需要 N/2 行对上的循环或 *apply 函数。
    猜你喜欢
    • 2017-10-07
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多