0

我有一组包含要转换为数据集的元素的字符串。本质上,我想删除空白并留下数据列。最简单的方法,也许是唯一的方法,我知道这样做是写入my.data外部文件,然后将该外部文件读回 R。是否有更有效的解决方案不涉及写入和读取新文件?感谢您的任何建议。我更喜欢base R。

my.data <- c('   abc        -1.10      1.18       -3.41      1.21 ',
             '    def        -1.71      0.21     -2.14    1.29      ',
             '   gg          2.19      2.93       -1.16       3.55   ',
             '  hvv4      0.00       -0.01           0.04     0.11       ')

my.data <- data.frame(my.data, stringsAsFactors=FALSE)

desired.result <- read.table(text = '

  parm1   beta    SE     lcl    ucl
   abc   -1.10   1.18  -3.41   1.21
   def   -1.71   0.21  -2.14   1.29
    gg    2.19   2.93  -1.16   3.55
   vv4    0.00  -0.01  -0.04   0.11

', header = TRUE, stringsAsFactors=FALSE)
4

2 回答 2

4

为什么不只read.table在你的字符串上使用?

out <- read.table(text = my.data, stringsAsFactors=FALSE, 
                  header = FALSE, strip.white=TRUE)
str(out)
# 'data.frame': 4 obs. of  5 variables:
#  $ V1: chr  "abc" "def" "gg" "hvv4"
#  $ V2: num  -1.1 -1.71 2.19 0
#  $ V3: num  1.18 0.21 2.93 -0.01
#  $ V4: num  -3.41 -2.14 -1.16 0.04
#  $ V5: num  1.21 1.29 3.55 0.11
于 2013-11-03T06:40:48.897 回答
1
x=t(unique(unlist(strsplit(x=my.data,split=" ")))[-1])
cleaned=matrix(x,5,4)
t(cleaned)

      [,1]    [,2]    [,3]    [,4]   
[1,] "abc"   "def"   "gg"    "hvv4" 
[2,] "-1.10" "-1.71" "2.19"  "0.00" 
[3,] "1.18"  "0.21"  "2.93"  "-0.01"
[4,] "-3.41" "-2.14" "-1.16" "0.04" 
[5,] "1.21"  "1.29"  "3.55"  "0.11" 

cleaned

      [,1]   [,2]    [,3]    [,4]    [,5]  
[1,] "abc"  "-1.10" "1.18"  "-3.41" "1.21"
[2,] "def"  "-1.71" "0.21"  "-2.14" "1.29"
[3,] "gg"   "2.19"  "2.93"  "-1.16" "3.55"
[4,] "hvv4" "0.00"  "-0.01" "0.04"  "0.11"
于 2013-11-03T07:16:26.633 回答