R: subsetting data frame by both certain column names (as a variable) and field values

社会主义新天地 提交于 2019-12-02 15:04:41

问题


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)


来源:https://stackoverflow.com/questions/17748958/r-subsetting-data-frame-by-both-certain-column-names-as-a-variable-and-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!