Arkning
Arkning

Reputation: 181

Is there a way to update argument for each call of lapply?

I'm using a function to update my dataframe, the first argument is the dataframe which I want to update, the second one is another dataframe which allows me to update the first one and the third argument is an integer.

I've already used lapply and other function which are similar but in this case I have some trouble to achieve what I want.

Here is an example of my dataframe :

df <- data.frame("Fa" = c("a", "b", "c", "a"),
                 "P" = c(1, 2, 3, 4), stringsAsFactors = FALSE)

Same for the other dataframe:

df2 <- data.frame("CF" = c("a", "b", "c"),
                  "R" = c(1, 2, 3),
                  "ND" = c(1, 2, 3),
                  "DD" = c(1, 2, 3),
                  "DF" = c(1, 2, 3),
                  "NF" = c(1, 2, 3),
                  "AAA" = c(1, 2, 3),
                  "BBB" = c(1, 2, 3),
                  "CCC" = c(1, 2, 3),
                  "DDD" = c(1, 2, 3),
                  "EEE" = c(1, 2, 3),
                  "FFF" = c(1, 2, 3),
                  "S" = c(1, 2, 3), stringsAsFactors = FALSE)

The function I'm using :

my_function <- function(x, y, nb) {
  x[which(x$Fam == as.character(y[nb, "CF"])), "PR"] <- x[which(x$Fam == as.character(y[nb, "CF"])), "P"] * (1 - as.double(y[nb, "R"]))
  x[which(x$Fa == as.character(y[nb, "CF"])), "R"] <- y[nb, "R"]
  x[which(x$Fa == as.character(y[nb, "CF"])), "ND"] <- y[nb, "ND"]
  x[which(x$Fa == as.character(y[nb, "CF"])), "DD"] <- y[nb, "DD"]
  x[which(x$Fa == as.character(y[nb, "CF"])), "DF"] <- y[nb, "DF"]
  x[which(x$Fa == as.character(y[nb, "CF"])), "NF"] <- y[nb, "NF"]
  x[which(x$Fa == as.character(y[nb, "CF"])), "S"] <- y[nb, "S"]
  return (x)
}

Example to see how the function is used :

df <- my_function(df, df2, 1)
df <- my_function(df, df2, 2)
df <- my_function(df, df2, 3)

Basically my aim is to avoid calling my function multiple times, so it's more clear why i've done it 3 times, it's because in my dataframe "df2" i have 3 rows. So I wanted to know if this could be achieve by using lapply or any other method or should I change my function ?

Upvotes: 0

Views: 47

Answers (1)

Iaroslav Domin
Iaroslav Domin

Reputation: 2718

Looks like you need a left join and mutate:

library(dplyr)
left_join(df, df2, by  = c("Fa" = "CF")) %>% 
  mutate(PR = P*(1 - R))
#>   Fa P R ND DD DF NF S PR
#> 1  a 1 1  1  1  1  1 1  0
#> 2  b 2 2  2  2  2  2 2 -2
#> 3  c 3 3  3  3  3  3 3 -6
#> 4  a 4 1  1  1  1  1 1  0

Upvotes: 1

Related Questions