R: subsetting data frame by both certain column na

2020-05-03 10:57发布

问题:

I have list of names and I have a data frame with colnames that match sometimes the names in the list. Now I want to subset the data frame based on two criteria: the colnames (as a variable) in the list and the values of the fields in those columns.

I tried it this way:

  names.list <- c("name1", "name2" , "name5")
   names <- as.data.frame(names.list)
   df <- *dataframe with colnames "name1", "name2", "name3", "name4", etc.*

   for (i in 1:nrow(names)){
   name <- names[i,1]
   df <- subset(df, name > 1.5)
   }

I know this is the wrong way, but I haven't figured out yet to do it properly. Does anyone know how to do this?

many thanks in advance!

回答1:

Use the old-fashioned [ and [[ operators:

name <- "name1"
df[df[[name]] > 1.5, ]
(etc)


标签: r subset