Code to import data from a Stack overflow query into R

后端 未结 4 912
长情又很酷
长情又很酷 2020-12-01 04:08

When I try to answer a question in Stack Overflow about R, a good part of my time is spent trying to rebuild the data given as example (unless the question author has been n

4条回答
  •  攒了一身酷
    2020-12-01 04:56

    Recent version of R now offer an even lower keystroke option than the textConnection route for entry of columnar data into read.table and friends. faced with this:

    zz
      a  b   c
    1 1 11 foo
    2 2 12 bar
    3 3 13 baz
    4 4 14 bar
    5 5 15 foo
    

    One can simply insert : <- read.table(text=" after the zz, delete the carriage-return and then insert ", header=TRUE) after the last foo and type [enter].

    zz<- read.table(text="  a  b   c
    1 1 11 foo
    2 2 12 bar
    3 3 13 baz
    4 4 14 bar
    5 5 15 foo", header=TRUE)
    

    One can also use scan to efficiently enter long sequences of pure numbers or pure character vector entries. Faced with: 67 75 44 25 99 37 6 96 77 21 31 41 5 52 13 46 14 70 100 18 , one can simply type: zz <- scan() and hit [enter]. Then paste the selected numbers and hit [enter] again and perhaps a second time to cause a double carriage-return and the console should respond "read 20 items".

    > zz <- scan()
    1: 67  75  44  25  99  37   6  96  77  21  31  41   5  52  13  46  14  70 100  18
    21: 
    Read 20 items
    

    The "character" task. after pasting to console and editing out extraneous line-feeds and adding quotes, then hitting [enter]:

    > countries <- scan(what="character")
    1:     'republic of congo'
    2:     'republic of the congo'
    3:     'congo, republic of the'
    4:     'congo, republic'
    5: 'democratic republic of the congo'
    6: 'congo, democratic republic of the'
    7: 'dem rep of the congo'
    8: 
    Read 7 items
    

提交回复
热议问题