问题
Okay, I am probably pursuing a roundabout way of accomplishing this, but I had a list called "goodAttributes
" and a dataframe called QTable
. If a column name of QTable
is in "goodAttributes
" than I want to return the max of that column, otherwise I want to return the minimum of the column...
I checked if the column name of QTable
was in the list "goodAttributes
" using "grepl
" and then reset the column names of QTable
if the value was in the list "goodAttributes
" as "True" and otherwise set the column name as "False
", and called the new table QTable2
.
Current DataFrame called "QTableB":
Now, if the column name of QTableB
is "True
" I want to find the maximum of that column, and if the column name of QTableB
is "False
" I want to return the minimum of that column... storing the results in a new data frame.
回答1:
One way to do this is to simply apply a function to all of the colnames
of the frame:
QTable <- data.frame(v1=1:10,v2=11:20,v3=31:40)
goodAttributes <- c("v1","v3")
sapply(colnames(QTable),function(c){
if(c %in% goodAttributes) max(QTable[,c])
else min(QTable[,c])})
which yields
v1 v2 v3
10 11 40
i.e. the max of v1 and v3 (the column names in goodAttributes
) and the min of v2.
来源:https://stackoverflow.com/questions/41900732/apply-a-function-if-column-name-is-in-a-list-in-r