Hello I have a dataframe like the below:
path.vec source.vec
1 apple Tuesday
2 lemon Monday
3 orange Wednesday
4c("apple", "lemon", "grape") c("Friday", "Monday", "Sunday")
5c("cheery", "lemon", "grape") c("Saturday", "Monday", "Sunday")
6c("apple", "lemon", "apple") c("Thursday", "Monday", "Sunday")
just 2 variables: path.vec and source.vec. Both are collecting 2 different shadows of the same data
[![enter image description here][1]][1]
I would like simply to swap elements between lists with same index when a condition is met.
Ratio should be:
if df$path.vec contains "apple" swap with df$source.vec same index element
I have tried the below:
df$path.vec <- ifelse(grepl("apple", df$path.vec), df$source.vec, df$path.vec)
but this is changing all the elements, when there is at least one element =="apple", while I want to change just the element "apple". I'm thinking that probably i need to find indexes first and after to base my swap on the index?
I have tried
ind <- which(df$path.vec %in% c("apple"))
but in my real data set this is an error
Error in `$<-.data.frame`(`*tmp*`, path.index, value = 1:6) :
replacement has 6 rows, data has 33422
because it's indexing just when apple is the only element of the list.
I have also tried
df$path.index <- match("apple", df$path.vec)
but this results just in 1 every single row of my dataframe.
Is this one the best way to approach this?
Eventually I would like to obtain another column like the below:
path.final
1 Tuesday
2 lemon
3 orange
4c("Friday", "lemon", "grape")
5c("cheery", "lemon", "grape")
6c("Thursday", "lemon", "Sunday")
Cheers,