简体   繁体   中英

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. 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

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

$B
[1] 1.772467

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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