使用多列作为变量与 sapply [英] use multiple columns as variables with sapply
本文介绍了使用多列作为变量与 sapply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 dataframe
,我想应用一个函数来获取三列的值并计算三个值之间的最小差异.
I have a dataframe
and I would like to apply a function that takes the values of three columns and computes the minimum difference between the three values.
#dataset
df <- data.frame(a= sample(1:100, 10),b = sample(1:100, 10),c= sample(1:100, 10))
#function
minimum_distance <- function(a,b,c)
{
dist1 <- abs(a-b)
dist2 <- abs(a-c)
dist3 <- abs(b-c)
return(min(dist1,dist2,dist3))
}
我正在寻找类似的东西:
I am looking for something like:
df$distance <- sapply(df, function(x) minimum_distance(x$a,x$b,x$c) )
## errormessage
Error in x$a : $ operator is invalid for atomic vectors
虽然我可以使用 ddply:
While I can use ddply:
df2 <- ddply(df,.(a),function(r) {data.frame(min_distance=minimum_distance(r$a,r$b, r$c))}, .drop=FALSE)
这不会保留所有列.有什么建议吗?
This doesn't keep all of the columns. Any suggestions?
我最终使用了:
df$distance <- mapply(minimum_distance, df$a, df$b, df$c)
推荐答案
尝试 mapply():
Try mapply():
qq <- mapply(minimum_distance, df$a, df$b, df$c)
这篇关于使用多列作为变量与 sapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文