Home > Net >  Using variable as column name not working when filtering or using subsets in R
Using variable as column name not working when filtering or using subsets in R

Time:11-30

I am trying to filter out all values above 0 in a column name, a variable I am getting from another CSV file.

When trying to filter on this value it does not work, returns 0 records like this: retA <- retnegative %>% filter(valname > 0)

I also tried retA <- retnegative %>% filter(as.numeric(valname) > 0)

this also does not work. How can I keep my valname a variable and still be able to filter through these values dynamically? Or is there another method to make this happen in R?

Full code:

# get our samplenames from other CSV
samples <- phenodata$samplename

# modify names to match names in pos and neg files.
negsamples <- paste(samples, "neg", sep = "-")

# for loop
for (val in negsamples) {
  # setup correct name format for R
  valname <- make.names(val)

  if (valname != "" & valname != "-neg") {
    print(valname)
    retA <- retnegative %>% filter(valname > 0)
    write.table(retA, paste("ResultNegData/", val, ".csv"), col.names = TRUE, sep = ",") # nolint
  }
}

Thanks in advance guys!

I am expecting the code to filter and give me all values for that column that are above 0

CodePudding user response:

filter doesn't recognise the string as a column name. You can parse it as an expression using base::parse or rlang::parse_expr (shown below):

library(tidyverse)
library(rlang)

for (val in names(mtcars[,c(8, 9, 11)])) {
  valname <- make.names(val)
  print(valname)
  filter(mtcars, !!parse_expr(valname) == 1) |> 
    head(3) |> 
    print()
}
#> [1] "vs"
#>                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Datsun 710     22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> Valiant        18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
#> [1] "am"
#>                mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> [1] "carb"
#>                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Datsun 710     22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> Valiant        18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
  • Related