[R] Addition operation based on specific columns and rows of twodata frames

Leeds, Mark (IED) Mark.Leeds at morganstanley.com
Sat Oct 13 00:29:42 CEST 2007


My guess is that there's  an easier way but this gives what you want.

newY.df<-aggregate(Y.df$Counts, list(Y.df[,1],Y.df[,2]), FUN=sum)
names(newY.df)<-names(X.df)

temp.df<-merge(newY.df, X.df,
by=intersect(names(X.df),names(newY.df)),all=TRUE) 

almost.df<-aggregate(temp.df$Counts, list(temp.df[,1],temp.df[,2]),
FUN=sum)

temp<-order(almost.df$Group.1)
final.df<-almost.df[temp,]
names(final.df)<-names(X.df)



-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Luke Neraas
Sent: Friday, October 12, 2007 5:15 PM
To: r-help
Subject: [R] Addition operation based on specific columns and rows of
twodata frames

#Hello,

# I have a question about the addition of values in specific columns and
rows of a Data frame.
# Below I have created two data frames, X.df and "Y.df".

## creation of X.df data frame

X<- matrix(0,16,3)
X.df<-data.frame(X)
X.df[,1] <- c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4)
X.df[,2] <- c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)
names(X.df)[1]<-"L(A)a(i)"
names(X.df)[2]<-"L(B)a(j)"
names(X.df)[3]<-"Counts"

X.df


## creation of Y.df data frame

Y<- matrix(0,7,3)
Y.df<-data.frame(Y)
Y.df[,1]<-c(1,3,4,2,2,1,2)
Y.df[,2]<-c(2,4,2,4,1,2,3)
Y.df[,3]<-c(1,2,1,0.5,1,1,1)
names(Y.df)[1]<-"L(A)a(i)"
names(Y.df)[2]<-"L(B)a(j)"
names(Y.df)[3]<-"Counts"

Y.df

# I would like to add the value in the "Counts" column of Y.df to the
"Counts" Column of X.df, based on matching # the row value from the
first two columns of each data.frame.  I have tried the "merge" function
but that # doesn't give me the addition operation.

# here is what i would like the resulting operation to end up with in
the X.df data frame

X.df$Counts <- c(0,2,0,0,1,0,1,0.5,0,0,0,2,0,1,0,0)


X.df


# Any help or ideas would be greatly appreciated

# Thanks in advance

# Luke Neraas

# lukasneraas.r at gmail.com

# University of Alaska Fairbanks
# School of Fisheries and Ocean Sciences # 11120 Glacier Highway # UAF
Fisheries Division # Juneau, AK 99801

	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
--------------------------------------------------------

This is not an offer (or solicitation of an offer) to bu...{{dropped:22}}



More information about the R-help mailing list