1

関数を使用して、大きなデータフレームをグループごとに補間する必要がありnlmます。単一のグループを持つ df で使用しても問題はありません。

#example data
df <- data.frame(var= cumsum(sort(rnorm(100, mean=20, sd=4))),
                 time= seq(from=0,to=550,length.out=100))
#create function
my_function <- function(Cini, time, theta,var){
  fy <- (theta[1]-(theta[1]- Cini)*exp((-theta[2]/100000)*(time-theta[3])))
  ssq<-sum((var-fy)^2)
  return(ssq)
}
th.start <- c(77, 148, 5)   #set starting parameters

#run nlm
my_fitt <- nlm(f=my_function, Cini=400, var = df$var,
               time=df$time, p=th.start)

次に、関数を使用して複数のグループを持つ df に関数を適用しようとしましたdlply

#data with groups
df.2 <- data.frame(var= cumsum(sort(rnorm(300, mean=20, sd=4))),
                   time= rep(seq(from=0,to=1200,length.out=100),3),
                   groups=rep(c(1:3),each=100))
#run nlm
library(plyr)
my_fitt.2 <- dlply(df.2, .(groups),
               nlm(f=my_function, Cini=400, var  = df.2$var,time=df.2$time, p=th.start))

ただし、次のメッセージが表示されますError in fs[[i]](x, ...) : attempt to apply non-function。また、この例でdf.2$取得し、元の df (は変数の 1 つ)を削除しようとしました。Error in time - theta[3] : non-numeric argument to binary operatorError in f(x, ...) : object 'time.clos' not foundtime.clos

さらに、dplyrライブラリを使用することをお勧めします

library(dplyr)
df.2 %>%
  group_by(groups) %>%
  nlm(f=my_function, Cini=400, v= var,
      time=time, p=th.start)

入手Error in f(x, ...) : unused argument (.)。何が問題なのですか?

4

2 に答える 2

1

tidyverse私は基本的な R のような人なので、環境についてはあまり役に立ちません。あなたの最後の呼び出しの問題は、最初の引数としてオブジェクトdata.frameを取る関数にグループをパイプしていることだと思います。functionそれはうまくいきません。

それを行う基本的なRの方法を提案させてください:

df.2 %>% 
  split(.$groups) %>% 
  lapply(function(xx) nlm(f=my_function, Cini=400, var = xx$var, time=xx$time, p=th.start))

これにより、list3 つの結果で長さ 3 (3 つのグループ) の が生成されます。

于 2018-07-31T12:56:51.870 に答える