Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use multiple columns as variables with sapply

Tags:

dataframe

r

apply

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 

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?

Edit: I ended up using:

df$distance <- mapply(minimum_distance, df$a, df$b, df$c) 
like image 782
zach Avatar asked Apr 09 '12 18:04

zach


People also ask

How do I use multiple columns in pandas?

Pandas apply() Function to Single & Multiple Column(s) Using pandas. DataFrame. apply() method you can execute a function to a single column, all and list of multiple columns (two or more).

How do I specify multiple columns in R?

To get multiple columns of matrix, specify the column numbers as a vector preceded by a comma, in square brackets, after the matrix variable name. This expression returns the required columns as a matrix.

What does across () do in R?

across() returns a tibble with one column for each column in .

Can pandas apply return multiple columns?

Return Multiple Columns from pandas apply() You can return a Series from the apply() function that contains the new data. pass axis=1 to the apply() function which applies the function multiply to each row of the DataFrame, Returns a series of multiple columns from pandas apply() function.


1 Answers

Try mapply():

qq <- mapply(minimum_distance, df$a, df$b, df$c) 
like image 67
geoffjentry Avatar answered Sep 19 '22 15:09

geoffjentry