Dynamic NROW Variable in read.csv, how to select all rows?

Viewed 59

Suppose I have a .csv file which I want to read.csv into R. Sometimes I want to use the "nrow" option to restrict the rows read into R. However other times I want all rows to be read in.

How do I add in a variable to dynamically code for the nrow option in read.csv?

For example:


want<-100

testdat<-read.csv("~/username/downloads/mycsv.csv",nrow=want)

The code chunk gives me dataset "testdat" with 100 rows.

Now suppose the mycsv.csv is 1000 rows long, now I want to set the "nrow" value to "all rows" without having to constantly delete and re-input the "nrow" option, I just would like to change the "want" variable.

2 Answers

We can use Inf as a value

want <- Inf
read.csv("~/username/downloads/mycsv.csv",nrows = want)

You can try with if else condition -

if(some_condition)
   testdat <- read.csv("~/username/downloads/mycsv.csv")
else 
  testdat <- read.csv("~/username/downloads/mycsv.csv", nrows = want)
Related