Reputation: 3781
I have a table like:
ex
dir E_numdir
45 OCAMPO 1253 2 1253, 2
74 BENITO LYNCH 1883 1883
24 PRESIDENTE DE LA PLA 148 148
Where E_numdir is a character I need to evaluate last 2 digits from each number in E_numdir, if they are 0 then get a mark in another column.
To evaluate this I tried:
lapply(ex$E_numdir , function(w) str_sub(w, -2, -1))
But I get the last 2 digits only from the last number.
So I tried:
lapply(as.vector(unlist(strsplit(ex$E_numdir,",")),mode="list") , function(w) str_sub(w, -2, -1))
But I get more rows than those I had. One for each element.
I need to get another column 'xx' with
dir E_numdir xx
45 OCAMPO 1253 2 1253, 2 53,2
74 BENITO LYNCH 1883 1883 83
24 PRESIDENTE DE LA PLA 148 148 48
How can I apply the function to all the numbers but store the result in the same row?
thanks.
Upvotes: 0
Views: 92
Reputation: 99321
You could do
library(stringi)
ex$last2 <- vapply(
## split on ", " - comma then a space
stri_split_fixed(ex$E_numdir, ", "),
## paste the last two characters of each element together
function(x) stri_c(stri_sub(x, -2), collapse = ","),
## set the return value for vapply()
character(1L)
)
which gives
dir E_numdir last2
1 45 OCAMPO 1253 2 1253, 2 53,2
2 74 BENITO LYNCH 1883 1883 83
3 24 PRESIDENTE DE LA PLA 148 148 48
Upvotes: 2