Reputation: 65
I'm hoping someone can help me with this challenge (I'm fairly new to R). I have one data frame (Plots) that has unique records for tree species (Spp) and tree size (Dbh). I have a second data frame (Parameters) that gives parameters (X and Y) for a function for each species.
Plots
Id Spp Dbh
414 SM 27.2
415 BE 17.4
416 YB 35.8
418 SM 43.5
419 SM 53.3
420 SM 53.3
421 SM 11.9
422 TL 27.5
423 XS 13.2
Parameters
Species X Y
BE 1 10
SM 2 20
YB 3 30
OTH 4 40
I need look at every record of Plots$Spp
and perform a simple function on Plots$Dbh
using the X
and Y
records from Parameters
(i.e. X * Dbh^Y
) for the corresponding Species
. If Plots$Spp
has a record that is not in Parameters$Species
(i.e. XS or TL), I need to use the X and Y values for OTH.
I first tried using merge()
but couldn't get it to work with the XS/OTH situation. I also tried a for loop with nested if/else if/else, but again I failed. Any help would be appreciated!
Upvotes: 0
Views: 54
Reputation: 19716
Perhaps this approach:
library(tidyverse)
Plots %>%
mutate(Species = ifelse(Spp %in% Parameters$Species, Spp, "OTH")) %>%
left_join(Parameters)
create a new variable "Species"
in Plots
data frame by first checking if Plots$Spp
is in Parameters$Species
if yes leave Spp
, if not replace with "OTH"
and then join the resulting data frame with Parameters
by "Species"
column.
#output
Id Spp Dbh Species X Y
1 414 SM 27.2 SM 2 20
2 415 BE 17.4 BE 1 10
3 416 YB 35.8 YB 3 30
4 418 SM 43.5 SM 2 20
5 419 SM 53.3 SM 2 20
6 420 SM 53.3 SM 2 20
7 421 SM 11.9 SM 2 20
8 422 TL 27.5 OTH 4 40
9 423 XS 13.2 OTH 4 40
data:
Plots <- read.table(text = "Id Spp Dbh
414 SM 27.2
415 BE 17.4
416 YB 35.8
418 SM 43.5
419 SM 53.3
420 SM 53.3
421 SM 11.9
422 TL 27.5
423 XS 13.2", header = T, stringsAsFactors = FALSE)
Parameters <- read.table(text = "Species X Y
BE 1 10
SM 2 20
YB 3 30
OTH 4 40", header = T, stringsAsFactors = FALSE)
Upvotes: 2