[R] reading from text file that have different rowlength and create a data frame

jim holtman jholtman at gmail.com
Mon Apr 4 16:01:27 CEST 2011


try this:

> x <- read.table(textConnection(";this is example
+ ; r help
+ Var1     Var2      Var3      Var4      Var5
+ 0             0.05     0.01        12
+ 1             0.04     0.06        18        A
+ 2             0.05     0.08        14
+ 3             0.01     0.06        15       B
+ 4             0.05     0.07        14       C")
+     , comment = ';'
+     , fill = TRUE
+     , header = TRUE
+     , na.strings = ''
+     )
> closeAllConnections()
>
> x
  Var1 Var2 Var3 Var4 Var5
1    0 0.05 0.01   12 <NA>
2    1 0.04 0.06   18    A
3    2 0.05 0.08   14 <NA>
4    3 0.01 0.06   15    B
5    4 0.05 0.07   14    C


On Mon, Apr 4, 2011 at 9:32 AM, Ram H. Sharma <sharma.ram.h at gmail.com> wrote:
> Hi R-experts
>
> I have many text files to read and combined them into one into R that are
> output from other programs. My textfile have unbalanced number of rows for
> example:
>
> ;this is example
> ; r help
> Var1     Var2      Var3      Var4      Var5
> 0             0.05     0.01        12
> 1             0.04     0.06        18        A
> 2             0.05     0.08        14
> 3             0.01     0.06        15       B
> 4             0.05     0.07        14       C
>
> and so on
> Inames<-as.data.frame(read.table("CLG1mpd.asc",header=T,comment=";"))
> Inames<-as.matrix(read.table("example.txt",header=T,comment=";"))
> Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,
> :
>  line 1 did not have 5 elements
>
>
> In bestcase scenerio, I want to fill the blank space with NA's, with matrix
> or dataframe
>  Var1     Var2      Var3      Var4      Var5
> 0             0.05     0.01        12        NA
> 1             0.04     0.06        18        A
> 2             0.05     0.08        14       NA
> 3             0.01     0.06        15       B
> 4             0.05     0.07        14       C
>
> The minimum would be to  remove the column Var5, so that my data.frame would
> look like the follows:
>  Var1     Var2      Var3      Var4
> 0             0.05     0.01        12
> 1             0.04     0.06        18
> 2             0.05     0.08        14
> 3             0.01     0.06        15
> 4             0.05     0.07        14
> --
> Thank you in advance for the help.
>
> Ram H
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list