0
votes

I have a table like:

                                       dir   E_numdir      last2
1                                          a          1          1
2 PJE INDEPENDENCIA 96 5                          96, 5     96,  5
3 PJE INDEPENDENCIA 96 5                          96, 5     96,  5
4 B 34 VIVIENDA RECRE 53 00                  34, 53, 00 34, 53, 00
5 SARMIENTO CASA DE GO 613                          613         13
6 ROCA 958 00 o                                 958, 00     58, 00

I need to evaluate each element of each row and if they are 00 store a list of 1 if they are 00 or 0 if they are not in each row.

I tried:

d$last1<-lapply(d$E_numdir, 
                function(w) lapply(strsplit(w,","),
                                   function(z) { 
                                     if(str_sub(z, -2, -1)==00){1}
                                   else {0}}))

But I get an error:

Error in if (str_sub(z, -2, -1) == 0) { : argument is of length zero

The desired result would be

                                       dir   E_numdir      last2      xx
1                                          a          1          1    0
2 PJE INDEPENDENCIA 96 5                          96, 5     96,  5    0,0 
3 PJE INDEPENDENCIA 96 5                          96, 5     96,  5    0,0
4 B 34 VIVIENDA RECRE 53 00                  34, 53, 00 34, 53, 00    0,0,1
5 SARMIENTO CASA DE GO 613                          613         13    0
6 ROCA 958 00 o                                 958, 00     58, 00    1,0

How can evaluate each element of each row with if function and store it in the same row?

EDITION: Structure of the table:

dput(d[1:2,c('dir', 'E_numdir', 'last2')]) structure(list(dir = c("a", "PJE INDEPENDENCIA 96 5 " ), E_numdir = c("1", "96, 5"), last2 = list(list("1"), list(c("96", " 5")))), .Names = c("dir", "E_numdir", "last2"), row.names = 1:2, class = "data.frame")

1

1 Answers

1
votes

Try

df$xx <- sapply(df$last2, function(x) toString((stri_split_fixed(x, ", ")[[1]] == "00") + 0))
df
#                          dir   E_numdir      last2      xx
# 1                          a          1          1       0
# 2     PJE INDEPENDENCIA 96 5      96, 5     96,  5    0, 0
# 3     PJE INDEPENDENCIA 96 5      96, 5     96,  5    0, 0
# 4 B 34 VIVIENDA RECRE 53 00  34, 53, 00 34, 53, 00 0, 0, 1
# 5   SARMIENTO CASA DE GO 613        613         13       0
# 6              ROCA 958 00 o   958, 00      58, 00    0, 1

Edit: If last2 is a list , you can simplify the code to just

df$xx <- sapply(df$last2, function(x) toString((unlist(x) == "00") + 0))