Reputation: 43
I have a boolean variable (parent_boolean). If parent_boolean = True then I want to apply a function to table_name, if parent_boolean = False then I want to apply a different function to table_name in the data set. What is the easiest way to do this in DPLYR?
table_name parent_table parent_boolean column_count
<chr> <chr> <lgl> <dbl>
1 table_1 table_1 TRUE 1
2 table_2 table_1 FALSE 3
dp_child <- function(table_name, parent_table) { function runs SQL statement against database)
dp_parent <- function(table_name) {function runs SQL statement against database)
I want to run the dp_parent function on each row that the table_name is the parent_table and I want to run the dp_child function on each row that the table_name is not the parent_table.
Upvotes: 0
Views: 955
Reputation: 101247
Here is a base R solution using ifelse()
, where a toy example is give as below
# two distinct function
f1 <- function(x) x**2
f2 <- function(x) -sqrt(x)
# apply function to column B according to value in column A
df <- data.frame(A = c(T,T,F,T),B = 1:4)
df <- within(df, C <- ifelse(A,f1(B),f2(B)))
such that
> df
A B C
1 TRUE 1 1.000000
2 TRUE 2 4.000000
3 FALSE 3 -1.732051
4 TRUE 4 16.000000
EDIT with the data frame in your post, maybe you can try the code below
result <- apply(df, 1, function(v) {
if (v["parent_boolean"]) {
dp_parent(v["table_name"])
} else {
dp_child(v["table_name"],v["parent_table"])
}
})
df <- cbind(df,result)
## or
# add_column(df, result)
Upvotes: 1
Reputation: 16178
You can use ifelse
in while creating a new column using mutate
:
A <- c(T,F,F,T,T)
B <- LETTERS[1:5]
df <- data.frame(A,B)
library(dplyr)
df %>% mutate(C = ifelse(A, paste0(B,1),paste0(B,"A")))
A B C
1 TRUE A A1
2 FALSE B BA
3 FALSE C CA
4 TRUE D D1
5 TRUE E E1
Does it answer your question ?
Upvotes: 1