使用多个列作为变量 [英] use multiple columns as variables with sapply

查看:119
本文介绍了使用多个列作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧,我想应用一个取三列值的函数,并计算三个值之间的最小值。

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)

这不保留所有o f列。任何建议?

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)

这篇关于使用多个列作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆