boop boop - 29 days ago 6
R Question

Writing data from one dataframe to a new column of another in R

I have two data frames in R.

data
, a frame with monthly sales per department in a store, looks like this:

dataframe named data

While
averages
, a frame with the average sales over all months per department, looks like this:

dataframe named averages

What I'd like to do is add a column to
data
containing the average sales (column 3 of
averages
) for each department. So whereas now I have an
avg
column with all zeroes, I'd like it to contain the overall average sales for whatever department is listed in that row. This is the code I have now:

for(j in 1:nrow(avgs)){
for(i in 1:nrow(data)){
if(identical(data[i,4], averages[j,1])){
gd[i,10] <- avgs[j,3] } } }


After running the loop, the
avg
column in
data
is still all zeroes, which makes me think that
if(identical(data[i,4], averages[j,1]))
is always evaluating to
FALSE
... But why would this be? How can I troubleshoot this issue / is there a better way to do this?

MFR MFR
Answer

Are you looking for merge function?

merge(x = data, y = avgs, by = "departmentName", all.x=TRUE)