私は、一定期間に与えられた年齢層に個人がどれだけ貢献したかを示す関数を作成しようとしています。指定された間隔で人が生きている場合、その人はその時間間隔に貢献します。例えば、年齢層0-1については、0.5歳で観察され、3歳で放置された個人は、0歳から1歳までの年齢に対して0.5歳に貢献する。
I've been able to run this code successfully over a for-loop, but it takes forever, so I'm trying to implement a vector-based function instead. The function works fine for individual entries, but cannot handle the vectors I pass to it, giving the error: "...the condition has length > 1 and only the first element will be used"
私が書いた関数は次のとおりです:
pyears01.smm <- function(ageent, ageleave) {
if ( is.na(ageent) | is.na(ageleave) )
{NA} else
if( ageent > 1 )
{0}
if ( ageent <= 1 && ageleave > 1 )
{1-ageent} else
if( ageent <= 1 && ageleave <= 1 )
{ageleave-ageent}
}
以下の評価には問題ありません。
pyears.smm(0,5)
[1] 1
pyears.smm(0.5,0.75)
[1] 0.25
pyears.smm(2,3)
[1] 0
NAを正しく評価していません。
> pyears.smm(NA,NA)
[1] 0
> pyears.smm("NA",5)
[1] 0
ベクトルを正しく処理しません:
x <- c(0,0.5,2,5)
y <- c(5,0.75,3,NA)
z<- pyears.smm(x,y)
Warning message:
In if (!is.na(ageent) & ageent <= 1 & !is.na(ageleave) & ageleave > :
the condition has length > 1 and only the first element will be used
> z
[1] 1.0 0.5 -1.0 -4.0
私はelseifがベクタを取りますが、このような文では単一の要素しか評価できないのですが、いくつかのネストされたif文があるので、これを修正する方法がわかりません。任意の提案をいただければ幸いです。ありがとう!