Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read odd numbered rows from csv file

Tags:

r

csv

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?

like image 290
user3174523 Avatar asked Jun 08 '26 22:06

user3174523


2 Answers

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).

like image 55
Sven Hohenstein Avatar answered Jun 10 '26 18:06

Sven Hohenstein


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),]
like image 33
nico Avatar answered Jun 10 '26 18:06

nico