samca12
samca12

Reputation: 17

How to create function to remove rows with certain strings in data frame list?

I have a data set similarly to the one below, I am attempting to remove all rows that have Totals or empty strings in the first column y1 across the data list.

d1 <- data.frame(y1 = c("", 2, 3),
                 y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c("Total", 2, 1),
                 y2 = c(6, 5, 4))
d3 <- data.frame(y1 = c(1, 2, 3),
                 y2 = c(4, 5, 6))
d4 <- data.frame(y1 = c("", 2, 1),
                 y2 = c(6, 5, 4))
d5 <- data.frame(y1 = c(1, "Total", 3),
                 y2 = c(4, 5, 6))
my.list <- list(d1, d2,d3,d4,d5)

I have tried a using lapply with mutate functions but I have not been able to find any fix across to the data frame list.

Upvotes: 1

Views: 26

Answers (1)

akrun
akrun

Reputation: 887241

We can use subset by looping over the list with lapply

my.list2 <- lapply(my.list, subset, subset = y1 != 'Total' & y1 != "")

Or with %in%

my.list2 <- lapply(my.list, subset, subset = !y1 %in% c("Total", ""))

Upvotes: 1

Related Questions