Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

r - creating functions to calculate the technical error and the coefficient of variation of the error

I have this equation (which can be accessed through this link):

enter image description here

I would like to create two functions by using r. The first one is by using the first equation provided.

The second function is to create a mathematical formula in which the first function is substituted. Here is the formula:

(http://i43.tinypic.com/b6vq5j.jpg)

THis is the head of my data: (data_1)

  sex age seca1 chad1  DL alog1 dig1 scifirst1 crimetech1
1   F  20  1754  1750 175    95   95       432        429
2   F  19  1594  1596 158    56   55       420        417
3   F  20  1556  1558 156    74   72       435        437
4   F  18  1648  1640 167    67   65       431        434
5   F  19  1780  1780 178    99   67       433        431
6   F  19  1610  1620 165    56   54       423        425

After doing this as @janos suggested:

f1 <- function(x, y) {sqrt(sum((x - y) ^ 2) / 2 / length(x))}

now, as i need to run f1 on data_1$alog1 vs data_1$dig1... here's what i did:

f1(data_1$alog1, data_1$dig1)

which gives: 4.3

Next, I tried to implement the 2nd formula like this:

f2 <- function(x, y){(f1 / ((x + y) / 2)) * 100}

but then, when I run it on data_1$alog1 vs data_1$dig1 to calculate the coefficient of variation of the error for these data I get:

> f2(data_1$alog1, data_1$dig1)
Error in f1/((x + y)/2) : non-numeric argument to binary operator

Could anyone please comment on the steps performed to create the first function, the second function and the way i run the functions on "alog1 vs dig1" ?

Thanks all!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understood correctly, here you go:

f1 <- function(x, y) {
  sqrt(sum((x - y) ^ 2) / 2 / length(x))
}
f1(1:3, 4:6)

This will output:

[1] 2.12132

The function assumes that x and y are both vectors of the same length.

You can do the same for the 2nd function, with some simplification:

f2 <- function(x, y) {
  200 * f1(x, y) / (x + y)
}
f2(1:3, 3:5)

To check that two vectors have the same length, you can use the length method. It can be also useful to halt execution if this assumption fails, like this:

stopifnot(length(x) == length(y))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...