2015-01-26 56 views
0

我有一个表,如:R- lapply一个列表

          dir  E_numdir 
45 OCAMPO 1253 2         1253, 2 
74 BENITO LYNCH 1883         1883 
24 PRESIDENTE DE LA PLA 148        148 

凡E_numdir是一个字符 我需要最后2个位数从E_numdir每个数字评估,如果是0然后在另一列中获得一个标记。

要评估这个我试过:

lapply(ex$E_numdir , function(w) str_sub(w, -2, -1)) 

但我只能从最后一个号码拿到最后2个位数。

所以,我想:

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

使用像'reshape2 :: colsplit'先清理你的数据,因此你不必在一列多个值被逗号隔开。 – joran 2015-01-26 20:48:16

回答

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