Here's my main dataset:
plot_no <-c(1,1,1,2,2,2,3,3,3,3,3)
basal_area <-c(3.5,4.1,6.0,0.9,4.4,4.8,0.7,3.2,3.6,5.5,1.8)
indiv_tree <-c(1,2,3,1,2,3,1,2,3,4,5)
df1<-data.frame(plot_no, basal_area, indiv_tree)
which looks like this:
plot_no basal_area indiv_tree
1 1 3.5 1
2 1 4.1 2
3 1 6.0 3
4 2 0.9 1
5 2 4.4 2
6 2 4.8 3
7 3 0.7 1
8 3 3.2 2
9 3 3.6 3
10 3 5.5 4
11 3 1.8 5
In another data frame I have summed the total basal_area for each plot_no, and these data are now in a data frame that looks like this:
plot_no total_basal
1 1 13.6
2 2 10.1
3 3 14.8
What I want to do is code a new variable in df1 where the total_basal value would match up with the plot_no value, producing this:
plot_no basal_area indiv_tree total_basal
1 1 3.5 1 13.6
2 1 4.1 2 13.6
3 1 6.0 3 13.6
4 2 0.9 1 10.1
5 2 4.4 2 10.1
6 2 4.8 3 10.1
7 3 0.7 1 14.8
8 3 3.2 2 14.8
9 3 3.6 3 14.8
10 3 5.5 4 14.8
11 3 1.8 5 14.8
I took a look at this question Create new variable in R data frame by conditional lookup but I suspect there's a simpler, more basic solution.
df1$total_basal <-df2$total_basal[df1$plot_no]and it writes the new column in df1 as expected.