英文:
R : Find Column with highest value
问题
我想找到每一列的最大值,并生成哪一列生成了最高值的信息(图片中的黄色单元格)。
感谢帮助。
英文:
I want to find the MAX value in each column and generate info of which column that generate the highest value (Yelow cell in the pic).
Thanks for help.
答案1
得分: 2
以下是翻译好的部分:
这是一个基本的R解决方案:
df <- cbind(df,
do.call(rbind,
apply(df[-1], 1, function(v) data.frame(MAX = max(v),Top_Subject = names(v[which.max(v)])))))
如此一来:
> df
Name Math Physics History Chemistry Biology MAX Top_Subject
1 Jack 9 8 7 7 4 9 Math
2 Andy 6 8 6 5 5 8 Physics
3 Peter 7 10 7 6 8 10 Physics
4 Ashley 7 6 5 6 8 8 Biology
数据
df <- structure(list(Name = c("Jack", "Andy", "Peter", "Ashley"), Math = c(9,
6, 7, 7), Physics = c(8, 8, 10, 6), History = c(7, 6, 7, 5),
Chemistry = c(7, 5, 6, 6), Biology = c(4, 5, 8, 8)), class = "data.frame", row.names = c(NA,
-4L))
英文:
Here is a base R solution
df <- cbind(df,
do.call(rbind,
apply(df[-1], 1, function(v) data.frame(MAX = max(v),Top_Subject = names(v[which.max(v)])))))
such that
> df
Name Math Physics History Chemistry Biology MAX Top_Subject
1 Jack 9 8 7 7 4 9 Math
2 Andy 6 8 6 5 5 8 Physics
3 Peter 7 10 7 6 8 10 Physics
4 Ashley 7 6 5 6 8 8 Biology
DATA
df <- structure(list(Name = c("Jack", "Andy", "Peter", "Ashley"), Math = c(9,
6, 7, 7), Physics = c(8, 8, 10, 6), History = c(7, 6, 7, 5),
Chemistry = c(7, 5, 6, 6), Biology = c(4, 5, 8, 8)), class = "data.frame", row.names = c(NA,
-4L))
答案2
得分: 0
以下是翻译好的部分:
一个基于R的解决方案(将来请复制并粘贴dput(df)函数的输出以生成示例,而不是图片):
df2 <- transform(df, max_scores = apply(df[,sapply(df, is.numeric)], 1, max),
top_sub_per_stud = names(df[,sapply(df, is.numeric)])[apply(df[,sapply(df, is.numeric)], 1, which.max)])
数据:
df <- structure(list(Name = c("Jack", "Andy", "Peter", "Ashley"), Math = c(9,
6, 7, 7), Physics = c(8, 8, 10, 6), History = c(7, 6, 7, 5),
Chemistry = c(7, 5, 6, 6), Biology = c(4, 5, 8, 8)), class = "data.frame", row.names = c(NA,
-4L))
英文:
A base R solution (in future please c+p the output of dput(df) function in order to generate the example instead of a picture):
df2 <- transform(df, max_scores = apply(df[,sapply(df, is.numeric)], 1, max),
top_sub_per_stud = names(df[,sapply(df, is.numeric)])[apply(df[,sapply(df, is.numeric)], 1, which.max)])
Data:
df <- structure(list(Name = c("Jack", "Andy", "Peter", "Ashley"), Math = c(9,
6, 7, 7), Physics = c(8, 8, 10, 6), History = c(7, 6, 7, 5),
Chemistry = c(7, 5, 6, 6), Biology = c(4, 5, 8, 8)), class = "data.frame", row.names = c(NA,
-4L))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论