Return column name for max function

偶尔善良 提交于 2020-04-16 02:44:10

问题


ethnicity_col_names <- c("surname", "first_name", "surname.match", "white", "black",
                     "hispanic", "asian", "other")
colnames(ethnicity_sample) <- ethnicity_col_names
ethnicity_sample$try <- pmax(ethnicity_sample$white, ethnicity_sample$black, ethnicity_sample$hispanic,
            ethnicity_sample$asian, ethnicity_sample$other)

Each one of the ethnicity categories returns a % likelihood of the person belonging to that ethnicity. When I use the pmax function, it returns the highest % (in numbers). I want it to return the name of the column with the ethnicity with the highest % match.


回答1:


We can use max.col to return the index of the columns with the max value for each row

nm1 <- c("white", "black", "hispanic", "asian", "other")
ethnicity_sample$try  <- nm1[max.col(ethnicity_sample[nm1], 'first')]


来源:https://stackoverflow.com/questions/60020924/return-column-name-for-max-function

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