2017-09-22 3 views
0

J'ai une base de données qui a plusieurs variables avec une chaîne (les variables), et j'essaie de déterminer si la chaîne dans les variables an apparaît dans la colonne string. Chaque variable an a une variable cn correspondante. Par exemple, je souhaite que c1 contienne Checked si la chaîne a1 apparaît dans string, et ainsi de suite. J'ai développé la solution de boucle ci-dessous pour cela (quelques exemples de données à la fin de ce post) mais je me demandais s'il y avait une solution de famille d'application à cela qui pourrait être plus rapide et plus facile à coder? Dans les données réelles, il existe plus de 100 variables a et c.Appliquer une solution de famille pour plusieurs boucles?

#For loop solution 

for (var in seq(2, 10, 2)){ 
    for (i in 1:nrow(df)){ 
    df[i, var]<-ifelse(grepl(df[i, var-1], df$string[i])=="TRUE", "Checked", "Unchecked") 
    } 
} 


#### Example data #### 
a1<-c("zebra", "giraffe", "elephant") 
a2<-c("hyena", "monkey", "antelope") 
a3<-c("badger", "deer", "kangaroo") 
a4<-c("tiger", "lion", "coyote") 
a5<-c("penguin", "bear", "gorilla") 

c1<-"" 
c2<-"" 
c3<-"" 
c4<-"" 
c5<-"" 

string<-c("elephant/bear/coyote/penguin/monkey", 
      "giraffe/antelope/monkey/gorilla/tiger", 
      "elephant/antelope/kangaroo/coyote/gorilla") 

df<-cbind.data.frame(a1, c1, a2, c2, a3, c3, a4, c4, a5, c5, string, 
stringsAsFactors=F) 

Répondre

0

Vous pouvez le faire. Généralisable à n'importe quel nombre de a.

require(dplyr) # For readability 
a<-cbind.data.frame(a1, a2, a3, a4, a5, stringsAsFactors=F) 

a %>% 
    sapply(function(x) {mapply(function(a) grepl(a, string), x) %>% diag}) %>% 
            # Check for condition in above line 
    ifelse("Checked", "Unchecked") %>% # Convert True and False to Checked and Unchecked 
    data.frame %>%      # Convert to data.frame 
    setNames(paste0("c", 1:5))   # Setnames 

     c1  c2  c3  c4  c5 
1 Unchecked Unchecked Unchecked Unchecked Checked 
2 Checked Checked Unchecked Unchecked Unchecked 
3 Checked Checked Checked Checked Checked 

dans la base R

c_column = data.frame(ifelse(sapply(a, function(x) diag(mapply(function(a) grepl(a, string), x))), "Checked", "Unchecked")) 
names(c_column) = paste0("c", 1:5) 
0

Cela fera ce que vous demandez, en utilisant sapply

df[,2*(1:5)] <- t(sapply(1:nrow(df), 
        function(i) sapply(2*(1:5)-1, 
         function(j) c("Unchecked","Checked")[1+grepl(df[i,j], df$string[i])] 
       ))) 

df 
     a1  c1  a2  c2  a3  c3  a4  c4  a5  c5         string 
1 zebra Unchecked hyena Unchecked badger Unchecked tiger Unchecked penguin Checked  elephant/bear/coyote/penguin/monkey 
2 giraffe Checked monkey Checked  deer Unchecked lion Unchecked bear Unchecked  giraffe/antelope/monkey/gorilla/tiger 
3 elephant Checked antelope Checked kangaroo Checked coyote Checked gorilla Checked elephant/antelope/kangaroo/coyote/gorilla