Levi
Levi

Reputation: 301

How to evaluate several column names in a function?

I am working with a very wide data frame that consists of 100+ column names. I am looking to structure the search for data in each of these columns using the following code:

funfilter <- function(col) {
    print(col)
    output <- d$col[d$col != ""]
    print(output)
}

for(i in 23:length(colnames(d))){
  funfilter(colnames(d)[i])
}

This code produces an output variable that is NULL. Is there a better way to accomplish this? I would prefer to use R-base if possible.

Upvotes: 0

Views: 63

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389145

You can use base lapply/sapply to achieve your output

lapply(d[23:ncol(d)], function(x) x[x != ""])

This will give you a list of vectors where the value in the column is not empty ("").

Using a reproducible example

d <- data.frame(a = 1:5, b = c(1, 2, 3, "", 4), c = c("", 1, "", 3, ""), 
                stringsAsFactors = FALSE)

lapply(d[2:ncol(d)], function(x) x[x != ""])

#$b
#[1] "1" "2" "3" "4"

#$c
#[1] "1" "3"

Upvotes: 1

Related Questions