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!
Use the old-fashioned [
and [[
operators:
name <- "name1"
df[df[[name]] > 1.5, ]
(etc)
来源:https://stackoverflow.com/questions/17748958/r-subsetting-data-frame-by-both-certain-column-names-as-a-variable-and-field