应用多个for循环的家庭解决方案?

时间:2017-09-22 16:00:29

标签: r for-loop apply

我有一个数据框,其中包含多个变量,其中包含一个字符串(sr1(IP(dst='192.168.1.1') / ICMP())变量),我正在尝试确定var x = 1; writeln(x.type:string); 变量中的字符串是否出现在a1, a2, ...an列中{{ 1}}。每个an变量都有一个对应的string变量。例如,如果an中的字符串显示在cn中,我希望c1中包含Checked,依此类推。我为此开发了以下for循环解决方案(本文末尾的一些示例数据),但我想知道是否有一个适用于此的应用系列解决方案可能更快更容易编码?在实际数据中,有超过100个a和c变量。

a1

2 个答案:

答案 0 :(得分:0)

这将使用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

答案 1 :(得分:0)

你可以这样做。可推广到任何数量的

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

在基地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)