I have the following df
datos2<-data.frame(
col1=c("rojo","rojo","verde","rojo","verde","rojo"),
col2=c(123,234,222,111,456,345),
col3=c("Esp 1",NA,NA,NA,"Psp 4",NA)
)
col1 col2 col3
1 rojo 123 Esp 1
2 rojo 234 <NA>
3 verde 222 <NA>
4 rojo 111 <NA>
5 verde 456 Psp 4
6 rojo 345 <NA>
I want to add to col3 the word Esp followed by the first digit of col2 only if col1 is red
Something like
ifelse(datos2$col1 =="rojo" & grepl("(\\d{1})", datos2$col2)....añadir Esp \\1 a la col3
The desired result is the following:
col1 col2 col3
1 rojo 123 Esp 1
2 rojo 234 Esp 2
3 verde 222 <NA>
4 rojo 111 Esp 1
5 verde 456 Psp 4
6 rojo 345 Esp 3
As long as you don't need anything with the current value of
col3
you could implement something like this:Detail:
col1 == "rojo"
we will use to select where we will make the changesgsub("(\\d{1}).*", "Esp \\1", datos2$col2[rojos])
, we capture the first digit ofCol2
and use it for the new pattern ofcol3
.I came up with the following code which solves your problem
I hope it helps you, regards