mercredi 5 décembre 2018

Nested ifelse with grepl function in R

i'm trying to lookup in 3 diff excel sheets(Data Frames) to add 3 new columns in the consolidated data frame.

df = Consolidated Data Frame where i'm trying to create 3 new columns

df2 = data frame(single column) where i'm looking up to get SheetName1 Column in df(SheetName1 column should result if df2 string found in any 5 columns from df else "NA"

df3 = ddata frame(single column) where i'm looking up to get Segregation & segregationRef Column in df(Segregation column should result if df3 string found in any 5 columns from df else "NA" segregationRef column should result "NA" if string found in segregation column. I tried the below but not getting the optimum result.

df$Sheetname1 <- "NA"

for(j in 1:nrow(df2)){
  for(k in 1:nrow(df)){
    df$Sheetname1[k]= ifelse(grepl(df2$Sheetname[j],paste(df$`Section Name`[k], df$ProductArea[k], df$SOURCE_CODE[k]),
                                   ignore.case = T),df2$Sheetname[j],df$Sheetname1[k])
    }
}

df$Segregation = NA
df$SegregationRef = 0

for(l in 1:nrow(df3)){
  for(m in 1:nrow(df)){
    df$Segregation[m]= ifelse(grepl(df3$Segregation[l],paste(df$`Section Name`[m], df$ProductArea[m], df$SOURCE_CODE[m],
                                                             df$`COLL MGR`[m], df$`Collateral Manager`[m]),ignore.case = T),
                                    df3$Segregation[l],df$Segregation[m])

  }
}

Aucun commentaire:

Enregistrer un commentaire