Replacing loop in dplyr R -
so trying program function dplyr withou loop , here not know how do
say have tv stations (x,y,z) , months (2,3). if group output summarised numeric value
tv months value x 2 52 y 2 87 z 2 65 x 3 180 y 3 36 z 3 99
this evaluated brand.
then have many brands need filter value >=0.8*value of evaluated brand & <=1.2*value of evaluated brand
so example down want filter first two, , should done months&tv combinations
brand tv month value sdg x 2 60 sdfg x 2 55 shs x 2 120 sdg x 2 11 sdga x 2 5000
as @akrun said, need use combination of merging , subsetting. here's base r solution.
m <- merge(df, data, by.x=c("tv", "month"), by.y=c("tv", "months")) m[m$value.x >= m$value.y*0.8 & m$value.x <= m$value.y*1.2,][,-5] # tv month brand value.x #1 x 2 sdg 60 #2 x 2 sdfg 55
data
data <- structure(list(tv = structure(c(1l, 2l, 3l, 1l, 2l, 3l), .label = c("x", "y", "z"), class = "factor"), months = c(2l, 2l, 2l, 3l, 3l, 3l), value = c(52l, 87l, 65l, 180l, 36l, 99l)), .names = c("tv", "months", "value"), class = "data.frame", row.names = c(na, -6l )) df <- structure(list(brand = structure(c(2l, 1l, 4l, 2l, 3l), .label = c("sdfg", "sdg", "sdga", "shs"), class = "factor"), tv = structure(c(1l, 1l, 1l, 1l, 1l), .label = "x", class = "factor"), month = c(2l, 2l, 2l, 2l, 2l), value = c(60l, 55l, 120l, 11l, 5000l)), .names = c("brand", "tv", "month", "value"), class = "data.frame", row.names = c(na, -5l))
Comments
Post a Comment