[英]Performing conditional (aka lookup) functions using two data frames?
I'm hoping someone can help me with this challenge (I'm fairly new to R). 我希望有人可以帮助我应对这一挑战(我对R很陌生)。 I have one data frame (Plots) that has unique records for tree species (Spp) and tree size (Dbh). 我有一个数据框(图),该树具有树种(Spp)和树大小(Dbh)的唯一记录。 I have a second data frame (Parameters) that gives parameters (X and Y) for a function for each species. 我有第二个数据框(参数),它为每个物种提供了函数的参数(X和Y)。
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
(ie X * Dbh^Y
) for the corresponding Species
. 我需要查看Plots$Spp
每条记录,并使用来自对应Species
Parameters
的X
和Y
记录(即X * Dbh^Y
)对Plots$Dbh
执行简单的功能。 If Plots$Spp
has a record that is not in Parameters$Species
(ie XS or TL), I need to use the X and Y values for OTH. 如果Plots$Spp
的记录不在Parameters$Species
(例如XS或TL),则需要对OTH使用X和Y值。
I first tried using merge()
but couldn't get it to work with the XS/OTH situation. 我首先尝试使用merge()
但无法使其与XS / OTH情况一起使用。 I also tried a for loop with nested if/else if/else, but again I failed. 我还尝试了使用嵌套if / else if / else的for循环,但同样失败了。 Any help would be appreciated! 任何帮助,将不胜感激!
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. 首先检查Plots$Spp
是否在Parameters$Species
如果是,则在Plots
数据框中创建一个新变量"Species"
。如果是,则保留Spp
,如果不替换为"OTH"
,然后将结果数据框与"Species"
列的Parameters
起来。
#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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.