简体   繁体   English

通过向量定义答案的函数

[英]Function defining answer by a vector

Looking to learn function writing. 期待学习函数写作。 I have data laid out in the following (eg): 我有以下数据(例如):

Genus Species  Wing  Tail
 A       X     10.5  20.3
 A       Y     10.7  20.7
 B       XX    15.2  22.5
 B       XY    15.5  24

I calculate variance for a given trait using the equation: 我使用以下等式计算给定特征的方差:

 sqrt(max(Wing) - min (Wing))

which I sum for all traits. 我总结了所有特质。

So I can write the following function so sum variance for the total data set: 所以我可以编写以下函数,以便总数据集的和方差:

variance<- function(data){
t   <- sqrt(max(Tail)-min(Tail))
w   <- sqrt(max(Wing)-min(Wing))
x <- sum(t,w)
x
}

But I can'twork out how to generate a response to give me an output where this result is dependant on the Genus. 但是我无法解决如何生成响应以提供输出的结果,该结果取决于Genus。 So i'm looking to generate an output like: 所以我希望生成如下输出:

 Genus A    Genus B
  2.345      3.456

I am going to give a new name to your function because it's just wrong to call it "variance". 我要给您的函数起一个新名字,因为称它为“方差”是错误的。 I hope you can overlook that. 我希望你能忽略这一点。 We can work on a dataframe object 我们可以处理数据框对象

dput(dfrm)
structure(list(Genus = structure(c(1L, 1L, 2L, 2L), .Label = c("A", 
"B"), class = "factor"), Species = structure(c(1L, 4L, 2L, 3L
), .Label = c("X", "XX", "XY", "Y"), class = "factor"), Wing = c(10.5, 
10.7, 15.2, 15.5), Tail = c(20.3, 20.7, 22.5, 24)), .Names = c("Genus", 
"Species", "Wing", "Tail"), class = "data.frame", row.names = c(NA, 
-4L))

dev2<- function(df){
    t   <- sqrt(max(df[["Tail"]])-min(df[["Tail"]]))
    w   <- sqrt(max(df[["Wing"]])-min(df[["Wing"]]))
    x <- sum(t,w)
   x
   }

Now use it to work on the full dataframe, using the split-lapply strategy, which passes sections of the original dataframe determined by the Genus values to the dev2 function 现在,使用拆分应用策略将其用于整个数据帧,该策略将由Genus值确定的原始数据帧的各个部分传递给dev2函数

lapply( split(dfrm, list(dfrm$Genus)), FUN = dev2)
$A
[1] 1.079669

$B
[1] 1.772467

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM