代码之家  ›  专栏  ›  技术社区  ›  tommy chheng

是否有方法使用read.csv从字符串值而不是R中的文件中读取?

  •  72
  • tommy chheng  · 技术社区  · 14 年前

    我正在编写一个R包,其中R代码与Java应用程序对话。Java应用程序输出一个CSV格式的字符串,我希望R代码能够直接读取字符串并将其转换为data.frame。

    5 回复  |  直到 7 年前
        1
  •  107
  •   fny    7 年前

    编辑一个7岁的答案: 许多的 更简单的原因是 text= 已添加到的参数 read.csv()

    R> data <- read.csv(text="flim,flam
    + 1.2,2.2
    + 77.1,3.14")
    R> data
      flim flam
    1  1.2 2.20
    2 77.1 3.14
    R> 
    

    是的,看看帮助 textConnection() --那个 R中的概念是基本上所有的读者(例如。 read.table() 及其变体)访问这些 连接 对象,该对象可以是文件、远程URL或来自其他应用程序的管道,或者。。。像你这样的短信。

    同样的技巧也用于所谓的here文档:

    > lines <- "
    + flim,flam
    + 1.2,2.2
    + 77.1,3.14
    + "
    > con <- textConnection(lines)
    > data <- read.csv(con)
    > close(con)
    > data
      flim flam
    1  1.2 2.20
    2 77.1 3.14
    > 
    

    注意这是一个 建造某物的方法,但它也是 因为所有数据的重复解析。从Java到R还有其他的方法,但这应该能让您快速进行。接下来是效率。。。

        2
  •  77
  •   Adam Bradley    12 年前

    注意,在当前版本的R中,您不再需要 textConnection() ,可以简单地执行以下操作:

    > states.str='"State","Abbreviation"
    + "Alabama","AL"
    + "Alaska","AK"
    + "Arizona","AZ"
    + "Arkansas","AR"
    + "California","CA"'
    > read.csv(text=states.str)
           State Abbreviation
    1    Alabama           AL
    2     Alaska           AK
    3    Arizona           AZ
    4   Arkansas           AR
    5 California           CA
    
        3
  •  4
  •   Joshua Ulrich    14 年前

    对。例如:

    string <- "this,will,be\na,data,frame"
    x <- read.csv(con <- textConnection(string), header=FALSE)
    close(con)
    #> x
    #    V1   V2    V3
    #1 this will    be
    #2    a data frame
    
        4
  •  1
  •   Roman LuÅ¡trik    14 年前

    假设您有一个名为tommy.csv的文件(是的,很有想象力,我知道……)包含

    col1 col2\n 1 1\n 2 2\n 3 3列

    此文件可以在以下帮助下读取 allowEscapes 论证 read.table

    > read.table("tommy.csv", header = TRUE, allowEscapes = TRUE)
    
      col1 col2
    1 col1 col2
    2    1    1
    3    2    2
    4    3    3
    

    这并不完美(修改列名…),但这只是一个开始。

        5
  •  0
  •   Richie Cotton Joris Meys    14 年前

    这个函数将Dirk的答案包装成一个方便的形式。这是一个很好的回答问题的方式,提问者刚刚把数据丢到了屏幕上。

    text_to_table <- function(text, ...)
    {
       dfr <- read.table(tc <- textConnection(text), ...)
       close(tc)
       dfr
    }
    

    要使用它,首先复制屏幕上的数据并粘贴到文本编辑器中。

    福巴巴兹
    12安
    34亿

    现在把它包起来 text_to_table ,引号和任何其他参数 read.table .

    text_to_table("foo bar baz
    1 2 a
    3 4 b", header = TRUE)
    
        6
  •  0
  •   Kiryl Varanovich    5 年前

    library(readr)
    read_csv(file = "col1, col2\nfoo, 1\nbar, 2")
    # A tibble: 2 x 2
     col1   col2
     <chr>  <dbl>
    1 foo       1
    2 bar       2