In pandas I frequently perform row wise operations with a custom function like this:
df = pd.DataFrame({'v1': [1, 2, 3], 'v2': [3, 4, 6], 'v3': [3, 4, 5]})
def f(row):
return(sum(row[["v1", "v3"]]) if row.v2 == 3 else 7)
df["new_col"] = df.apply(f, 1)
What would the equivalent be in dplyr?
Note that function f can possibly use many variables, not just v1-v3, so I would prefer not to name them all when calling the function.
edit: Example code of what I have currently in R. In this solution I am passing a pronoun object, which I am in doubt whether is appropriate.
d <- tibble(v1 = c(1,2,3), v2 = c(3,4,6), v3 = c(3,4,5))
f <- function(row){
if (row$v2 == 3) sum(something?) else 7
}
d %>% rowwise() %>% mutate(new_column = f(.data)) %>% ungroup()
edit2: Expected output. (Index column not important)
v1 v2 v3 new_col
0 1 3 3 4
1 2 4 4 7
2 3 6 5 7
Note: I am not looking for a solution to this specific problem. I am interested in a general way to pass rows to a function in R / dplyr, like apply() would in pandas.