0

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.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Levi
  • 301
  • 3
  • 12
  • 1
    it's unclear what you're trying to accomplish - can you make your example [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? You'll get better answers if so. – Chase Apr 02 '19 at 04:20
  • You can't use `$` to pass an argument in to a function - you need to use `[` or `[[` brackets like `fun <- function(col) { d[ d[[col]] != "" , ] }` and `fun("nameofcolumn")` – thelatemail Apr 02 '19 at 04:28

1 Answers1

1

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"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213