Alexander.Herr at csiro.au
2016-Jul-22 02:45 UTC
[R] adding new values to dataframe based on existing values in two columns
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