This seems fairly simple, I need to read only odd numbered rows from a data file in R and create a new data frame. How can I achieve this?
read.csv("filename.csv")[c(TRUE, FALSE), ]
How it works:
The function read.csv is used to read the whole file and returns a data frame including all rows. Then, [x, ] is used for extracting certain rows from the data frame. If the vector length of c(TRUE, FALSE) (2) is below the number of rows of the data frame, the vector values will be recycled until the length of the vector matches the number of rows. If the data frame has, e.g., 5 rows, the vector is c(TRUE, FALSE, TRUE, FALSE, TRUE). All rows corresponding to TRUE will be selected. Hence, this will select rows with odd row numbers.
By the way: If you want to select even row numbers, you can use c(FALSE, TRUE).
The easiest thing is to read the whole file and then only get the odd lines.
df <- read.csv("filename.csv")
df <- df[seq(1, nrow(df), 2),]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With