R - 灵活的条件

问题描述 投票:0回答:2

我有下面的R声明。基本上它遍历整个matchesData数据框并检查每行的条件是否匹配。

如果匹配,则在matchesData $ isRedPreferredLineup上放置一个'1'。

matchesData$isRedPreferredLineup <- ifelse((matchesData$redTop==red_poplist[1] & 
                                              matchesData$redADC==red_poplist[2] & 
                                              matchesData$redJungle==red_poplist[3] & 
                                              matchesData$redSupport==red_poplist[4] & 
                                              matchesData$redMiddle==red_poplist[5]  & 
                                              matchesData$YearSeason==Season), 1, 
                                           matchesData$isRedPreferredLineup)

但是,现在我需要条件灵活。意思是,如果

matchesData$redTop==red_poplist[1]
matchesData$redADC==red_poplist[2]
matchesData$redJungle==red_poplist[3]

条件匹配,或者如果

matchesData$redJungle==red_poplist[3]
matchesData$redSupport==red_poplist[4]
matchesData$redMiddle==red_poplist[5]

条件匹配,或者包含以下3个或多个条件的任何其他排列匹配,我想在matchesData $ isRedPreferredLineup上放置'1'。

(matchesData$redTop==red_poplist[1] & 
matchesData$redADC==red_poplist[2] & 
matchesData$redJungle==red_poplist[3] & 
matchesData$redSupport==red_poplist[4] & 
matchesData$redMiddle==red_poplist[5]  & 
matchesData$YearSeason==Season)

我怎么能在像这样的矢量化ifelse语句中这样做?或者有更好的方法吗?

请耐心等待,我对R.很新。谢谢。

r
2个回答
1
投票

也许这可行:

selectIndex <- apply(matchesData,1,function(row){
  sum(c(row['redTop']     == red_poplist[1],
        row['redADC']     == red_poplist[2],
        row['redJungle']  == red_poplist[3],
        row['redSupport'] == red_poplist[4],
        row['redMiddle']  == red_poplist[5],
        row['YearSeason'] == Season) > 3)
})
matchesData$isRedPreferredLineup[selectIndex] <- 1

1
投票

您可以像这样向量化TRUE / FALSE语句:

my.conditions <- cbind(matchesData$redTop==red_poplist[1], matchesData$redADC==red_poplist[2], 
                 matchesData$redJungle==red_poplist[3], matchesData$redSupport==red_poplist[4],
                 matchesData$redMiddle==red_poplist[5], matchesData$YearSeason==Season)

然后你可以考虑S1 <- rowSums(my.conditions),它会给你TRUE中的my.conditionss数量然后( 你的最终状况将归结为ifelse(S1 > 2, 1, ...) ) 考虑以下:

matchesData$isRedPreferredLineup[which(S1 > 2)] <- 1
© www.soinside.com 2019 - 2024. All rights reserved.