1

So I have a function flip.allele(a, b, c, d) which takes in 4 arguments and then returns a numerical value based on comparing these different arguments. I am now trying to write an additional function which will take this function and then apply it to a whole data frame, so iterate my the original function across every row in the data frame.

So the four values I want to compare are in columns 2, 3, 4, 5. And I want it to output the value of comparing those four columns into a new column 6.

This is my current attempt at doing this:

flip.data.frame = function(df) {

  for (i in nrow(df)) {

    df$flip = flip.allele(df[2], df[3], df[4], df[5])
  }
}

The issue is that all of my attempts so far (including this one) have meant that when trying to use it on my data, it takes the first 4 values, correctly applies the flip.allele function and then returns the value for that row into every single row in the data frame.

I know that this is because of the way I'm using the df$flip = bit, but I'm also not sure what a solution would be. I saw another thread which seemed to suggest using apply() but I'm not completely certain how to go about using that.

Any help appreciated.

Sabor117
  • 111
  • 1
  • 11

1 Answers1

1

We can use apply with MARGIN=1.

apply(df[2:5], 1, function(x) flip.allele(x[1], x[2], x[3], x[4]))

Or using pmap

library(tidyverse)
pmap(setnames(df[2:5], letters[1:4]), flip.allele)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • For the former possibility should it be as you've written it or did you mean it should be: ```apply(df[2:5], 1, flip.allele(df) flip.allele(df[1], df[2], df[3], df[4]))``` If it is as you've written it, then I'm not completely sure what the ```function(x)``` part of that is doing, could you possibly explain it? Similarly, what exactly is ```pmap``` doing? – Sabor117 Nov 01 '18 at 16:42
  • @Sabor117 according to your description in the post, you want to apply the function for each row. using the values of the columns. The `apply`, is doing that. It loops through the row of the columns 2:5 and apply the `flip.allele` function – akrun Nov 01 '18 at 16:45