[R] adding new values to dataframe based on existing values in two columns
Alexander.Herr at csiro.au
Alexander.Herr at csiro.au
Mon Jul 25 03:30:10 CEST 2016
Here is another solution using interaction, aggregate and merge:
interaction(xyz[,1],xyz[,2])->nf #create a unique x.y grouping
cbind(xyz[,1:2],nf)
aggregate(xyz[,3],list(nf),min)->nmins
names(nmins)<-c('nf','mins.1')
xyz$nf<-nf
merge(xyz,nmins, by='nf', all=TRUE)->nd
head(nd)
any other improvements?
XXXXXXXXXXXXXXX Herry wrote XXXXXXXXXXXXXXXXXX
Hiya,
I am trying to assign minimum values to a dataframe based on existing columns. I can do this via loops, but surely R has much more elegant solutions...
Here is my code:
set.seed(666)
xyz<-as.data.frame(cbind(x=rep(rpois(50,10),2)+1, y=rep(rpois(50,10),2)+1,z=runif(100, min=-3, max=40)))
xyz[order(xyz[,1], xyz[,2]),]->xyz
unique(xyz[,1:2])
dim(xyz)
aggregate(xyz[,3],by=list(x=xyz[,1],y=xyz[,2]), min)->mins
xyz$mins<-rep(NA, nrow(xyz))
#now assign min values to each xy combination
for(i in unique(xyz[,1])) {
mins[mins[,1]==i,]->mm
for( j in unique(mm[,2])) {
mins[mins[,1]==i & mins[,2] == j,3]->xyz[xyz[,1]==i & xyz[,2]==j,4]
}
}
Thanks and cheers
Herry
More information about the R-help
mailing list