Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

I have a dataframe with multiple columns. For each row in the dataframe, I want to call a function on the row, and the input of the function is using multiple columns from that row. For example, let's say I have this data and this testFunc which accepts two args:

> df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))

> df

  x y z

1 1 3 5

2 2 4 6

> testFunc <- function(a, b) a + b

Let's say I want to apply this testFunc to columns x and z. So, for row 1 I want 1+5, and for row 2 I want 2 + 6. Is there a way to do this without writing a for loop, maybe with the apply function family?

I tried this:

> df[,c('x','z')]

  x z

1 1 5

2 2 6

> lapply(df[,c('x','z')], testFunc)

Error in a + b : 'b' is missing

But got error, any ideas?

EDIT: the actual function I want to call is not a simple sum, but it is power.t.test. I used a+b just for example purposes. The end goal is to be able to do something like this (written in pseudocode):

df = data.frame(

    delta=c(delta_values), 

    power=c(power_values), 

    sig.level=c(sig.level_values)

)

lapply(df, power.t.test(delta_from_each_row_of_df,           power_from_each_row_of_df, 

sig.level_from_each_row_of_df

))

where the result is a vector of outputs for power.t.test for each row of df.

1 Answer

0 votes
by
edited by

You can use the apply function on each row of a data frame, with multiple columns from each row, as follows:

dt <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))

testFunc <- function(a, b) a + b

apply(dt[,c('x','z')], 1, function(x) testFunc(x[1],x[2]))

[1] 6 8

You can also use the mutate function from the dplyr package, as follows:

library(dplyr)

myfun <- function(a, b) { a + b }

 x <- data.frame(x = 1:2, y = 3:4, z = 5:6)

mutate(x, value = myfun(x, z))

  x y z value

1 1 3 5     6

2 2 4 6     8

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...