Re: [问题] 多个变量的循环如何处理?

楼主: abc2090614 (casperxdd)   2016-12-24 05:28:17
※ 引述《f496328mm (为什么会流泪)》之铭言:
: max.id=function(x2,name){
: value = name[ max(x2) == x2 ]
: return(value)
: }
: x=matrix(rnorm(20),ncol=4)
: name=c("A","B","C","D","E")
: rownames(x)=name
: x
: tem = apply(x,2,function(x) max.id(x,name))
: tem
: 应该还有更好的方法
: 我先提供一个
: 主要就是利用apply进行col运算
我来试一个 dplyr + reshape2 的解法
test.frame <- data.frame(
name = c("A","B","C","D","E"),
var1 = c(12,9,10,-5,2),
var2 = c(9,29,30,29,1)
)
library(reshape2)
library(dplyr)
test.frame %>% melt %>% group_by(variable) %>% filter(value == max(value))
得到的output如下
name variable value
<fctr> <fctr> <dbl>
1 A var1 12
2 C var2 30

Links booklink

Contact Us: admin [ a t ] ucptt.com