我有一张表:
离
dir E_numdir
45 OCAMPO 1253 2 1253, 2
74 BENITO LYNCH 1883 1883
24 PRESIDENTE DE LA PLA 148 148
E_numdir是一个角色 我需要评估E_numdir中每个数字的最后2位数,如果它们是0则在另一列中得到一个标记。
为了评估这一点,我尝试了:
lapply(ex$E_numdir , function(w) str_sub(w, -2, -1))
但我只从最后一个号码得到最后两位数字。
所以我试过了:
lapply(as.vector(unlist(strsplit(ex$E_numdir,",")),mode="list") , function(w) str_sub(w, -2, -1))
但是我的行数比我的行多。每个元素一个。
我需要另外一栏' xx'与
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
如何将函数应用于所有数字,但将结果存储在同一行?
感谢。
答案 0 :(得分:2)
你可以做到
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)
)
给出了
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