Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

Can anyone please tell me how to read only the first 6 months (7 columns) for each year of the data below, for example by using read.table()?

Year   Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec   

2009   -41  -27  -25  -31  -31  -39  -25  -15  -30  -27  -21  -25

2010   -41  -27  -25  -31  -31  -39  -25  -15  -30  -27  -21  -25 

2011   -21  -27   -2   -6  -10  -32  -13  -12  -27  -30  -38  -29

1 Answer

0 votes
by

To read only selected columns from a file, you can use the fread function from the data.table package as follows:

To create a file to read data:

df <- data.frame(Year = 2009:2011,

                  Jan = c(-41L, -41L, -21L), 

                  Feb = c(-27L, -27L, -27L), 

                  Mar = c(-25L, -25L, -2L), 

                  Apr = c(-31L, -31L, -6L),

                  May = c(-31L, -31L, -10L),

                  Jun = c(-39L, -39L, -32L),

                  Jul = c(-25L, -25L, -13L), 

                  Aug = c(-15L, -15L, -12L), 

                  Sep = c(-30L, -30L, -27L), 

                  Oct = c(-27L, -27L, -30L), 

                  Nov = c(-21L, -21L, -38L), 

                  Dec = c(-25L, -25L, -29L))

write.table(df, file = "data.txt", row.names = FALSE)

To read only selected columns:

library(data.table)

dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))

dat

   Year Jan Feb Mar Apr May Jun

1: 2009 -41 -27 -25 -31 -31 -39

2: 2010 -41 -27 -25 -31 -31 -39

3: 2011 -21 -27  -2  -6 -10 -32

You can also use the colClasses argument of the read.table() function to skip the columns as follows:

 read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)), 

                    header = TRUE)

  Year Jan Feb Mar Apr May Jun

1 2009 -41 -27 -25 -31 -31 -39

2 2010 -41 -27 -25 -31 -31 -39

3 2011 -21 -27  -2  -6 -10 -32

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...