在R特定情况下使用%>%

时间:2016-12-20 16:25:07

标签: r dplyr

我想使用R中dplyr包中的pipe函数来重写这段代码:

library(dplyr)

parking_information <- restaurant_information 
parking_information <- parking_information[!parking_information$PlaceID 
                                       %in% payment$PlaceID, ]
parking_information <- parking_information[-which(is.na
             (as.numeric(parking_information$Parking_Lot))), ]

我想做的是:

parking_information <- restaurant_information %>%
[!parking_information$PlaceID %in% payment$PlaceID, ] %>%
[-which(is.na(as.numeric(parking_information$Parking_Lot))), ]

但是,这会产生错误,并且它位于[]括号内。它确实看起来不错,但我真的不知道如何让它发挥作用。您的建议将不胜感激!

2 个答案:

答案 0 :(得分:3)

您忘记了对.进行操作所需的parking_information。请参阅magrittr documentation

parking_information <- restaurant_information %>%
.[!parking_information$PlaceID %in% payment$PlaceID, ] %>%
.[-which(is.na(as.numeric(parking_information$Parking_Lot))), ]

答案 1 :(得分:0)

library(dplyr)

parking_information <- restaurant_information %>%
    filter(!(PlaceID %in% payment$PlaceID), 
           !is.na(as.numeric(Parking_Lot)))

如果您想充分利用%>%

library(dplyr)

parking_information <- restaurant_information %>%
    filter(!(PlaceID %in% payment$PlaceID), 
           !(Parking_Lot %>% as.numeric() %>% is.na()))