Skip to content
Prev 360302 / 398506 Next

Data reshaping with conditions

Hi sri,
As your problem involves a few logical steps, I found it easier to
approach it in a stepwise way. Perhaps there are more elegant ways to
accomplish this.

svdat<-read.table(text="Count id name type
117 335 sally A
19 335 sally A
167 335 sally B
18 340 susan A
56 340 susan A
22 340 susan B
53 340 susan B
135 351 lee A
114 351 lee A
84 351 lee A
80 351 lee A
19 351 lee A
8 351 lee A
21 351 lee A
88 351 lee B
111 351 lee B
46 351 lee B
108 351 lee B",header=TRUE)
# you can also do this with other reshape functions
library(prettyR)
svdatstr<-stretch_df(svdat,"id",c("Count","type"))
count_ind<-grep("Count",names(svdatstr))
type_ind<-grep("type",names(svdatstr))
svdatstr$maxA<-NA
svdatstr$maxB<-NA
svdatstr$x<-NA
svdatstr$y<-NA
for(row in 1:nrow(svdatstr)) {
 svdatstr[row,"maxA"]<-
  max(svdatstr[row,count_ind[as.logical(match(svdatstr[1,type_ind],"A",0))]])
 svdatstr[row,"maxB"]<-
  max(svdatstr[row,count_ind[as.logical(match(svdatstr[1,type_ind],"B",0))]])
 svdatstr[row,"x"]<-svdatstr[row,"maxA"] < svdatstr[row,"maxB"]
 svdatstr[row,"y"]<-!svdatstr[row,"x"]
}
svdatstr

You can then just extract the columns that you need.

Jim
On Wed, Apr 20, 2016 at 3:03 PM, sri vathsan <srivibish at gmail.com> wrote: