this question has answer here:
sorry if asking trivial question, fact have spent few hours reading answers in data base , not find looking for.
i have dataframe similar
df=data.frame(v1=c(24,15, 0, 7,36,10), c1=c(22,15,0,0,28,11), v2=c(0,10,0,19,0,0), c2=c(0,7,0,22,0,0), v3=c(54,22,28,55,62,38), c3=c(44,23,22,66,71,44)) (the original, of course, has many more rows , columns)
i create 2 columns maximum , second highest values of "v" columns.
for maximum, works:
df$max.v=mapply(fun=max, df$v1, df$v2, df$v3, na.rm=true) but cannot find way second highest value. needs kind of function, not find how it.
note accepted answer in question linked @krlmlr dubious, because apply can break data frames. doesn't matter in case, because columns must numeric question make sense, prefer err on safe side.
instead, use do.call mapply, , persuade treat df list:
do.call(mapply, c(function(...) sort(c(...), dec=true)[1:2], df[grepl("v", names(df))]))
Comments
Post a Comment