1

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.

3
  • OK, I think I worked it out with some help from this answer stackoverflow.com/questions/49908674/…. Commented Jul 26, 2018 at 14:06
  • I put just the sums into a vector in a dataframe called df2, then created a new column in df1 using df1$total_basal <-df2$total_basal[df1$plot_no] and it writes the new column in df1 as expected. Commented Jul 26, 2018 at 14:08
  • Hmm, not so fast. Looks like that only works if the indexing variable consists of integers. What if I want to match a string? Commented Jul 26, 2018 at 18:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.