I extracted a vector
from a dataframe
.
The df
looks like this:
from type
23 U
25 U
30 S
32 S
50 T
60 T
and the vector
:
vec<-c("23","30","50")
Now I want to search for the values defined by the vector
in the df
.
If the value in the df
is part of the vector
then I want to paste the type
variable in front of the from
variable.
I tried to look up the vector
with dplyr::filter
.
df<-df %>% filter(from %in% vec && type=="U") %>% mutate(from=paste(type,from,sep=""))
Now I don't know how to proceed as my approach doesn't work out. Not sure whether a if-else
statement would be more appropriate.
expected results are:
from type
U23 U
25 U
S30 S
32 S
T50 T
60 T
Thank you in advance!
You could do:
df %>%
mutate(from = ifelse(from %in% vec, paste0(type, from), from))
from type
1 U23 U
2 25 U
3 S30 S
4 32 S
5 T50 T
6 60 T
Data:
df <- read.table(text = "
from type
23 U
25 U
30 S
32 S
50 T
60 T", h =T)
vec<-c("23","30","50")