How to delete even rows in text file

I loaded the txt file to R and found out that every even rows are filled with "".
How can I delete these rows?

Apologies up front if I'm simplifying too much.

I'm going to assume that you have the data as a character vector, text_raw, with one element per row of the original text file. You could then do the following (you could easily combine these steps into one concise line, but I'll keep it separate so you can follow along):

all_row_indices  <- 1:length(text_raw)
even_rows        <- (all_row_indices %% 2) == 0
text             <- text_raw[even_rows]
  • I used the length function to find how many rows you have, and made a vector of integers out of that using :;
  • used the modulo operator %% in combination with the equality check == to find the even rows* (test with commands like 1:10 %% 2 and (1:10 %% 2) == 0 to see what's going on);
  • and finally got the even rows out of the original vector using [.

*) with finding even rows, I mean getting a vector that says TRUE for every even index, and FALSE for every odd index.

# For more details on subsetting type this in the console:
# And for the other functions/operators mentioned:

P.S. a more concise version would look like this:

text <- text_raw[1:length(text_raw) %% 2 == 0]

Quick edit: if you're sure that every blank row is erroneous (not just the even ones), then simply using text <- text_raw[text_raw != ""] will also work. It uses the same logic described above.

I think you have a dataframe with even rows (assuming all columns) filled with "" as belows.
You can just filter them to get rid of those rows.

#>      V1 V2 V3   V4
#> 1 Hello  I am here
#> 2                 
#> 3 Hello  I am here
#> 4
#> [1] "Hello" ""      "Hello" ""
df %>% filter(!(V1 == "" & V2 == "" & V3 == "" & V4 == ""))
#>      V1 V2 V3   V4
#> 1 Hello  I am here
#> 2 Hello  I am here

Or, if we simply try to remove all even rows (2, 4,6,..), you can do

df %>% filter ( !as.numeric(rownames(.)) %% 2 == 0)
#>      V1 V2 V3   V4
#> 1 Hello  I am here
#> 2 Hello  I am here

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.