I have the following dataframe
v w e
dog cat ->
frog cat ->
frog dog ->
frog fish ->
fish cat ->
This is the function I wrote. It will output an updated dataframe based on the user input. The inputs V, W, and E can be a single string or a list. But V, W, and E must have the same length.
convert_df <- function(df, V, W, E) {
df %>%
dplyr::mutate(flag = (v %in% V & w %in% W | w %in% V & v %in% W),
txt = ifelse(flag, paste(V,E,W), paste(v,e,w)))
}
For example, this would be my expected output for the following. As you can see I want to change the txt column dog <-> frog and cat <-> dog :
> V <- c('dog', 'cat')
> W <- c('frog', 'dog')
> E <- c('<->', '<->')
> convert_df(df,V,W,E)
v w e
dog cat <->
frog cat ->
frog dog <->
frog fish ->
fish cat ->
However my function will output
dog cat <->
frog cat <->
frog dog <->
frog fish ->
fish cat ->
How can i fix my function? The indexes for V,W, and E are aligned to what i want to change in the dataframe. And my current function just checks if the v and w are in V and W regardless of the index alignment.
UPDATE:
Here I switch the order of V and W for the first element. I want to make my function dynamic so that the following would give the expected result as well:
> V <- c('frog', 'cat')
> W <- c('dog', 'dog')
> E <- c('<->', '<->')
> convert_df(df,V,W,E)
v w e
dog cat <->
frog cat ->
frog dog <->
frog fish ->
fish cat ->