R

时间:2017-03-20 11:41:35

标签: r data.table

我希望通过系列计算累计pnorm

set.seed(10)
df = data.frame(sample = rnorm(10))
# head(df)
#   sample
# 1  0.01874617
# 2 -0.18425254
# 3 -1.37133055
# 4 -0.59916772
# 5  0.29454513
# 6  0.38979430

我希望结果是

# na
# 0.2397501   # last value of pnorm(df$sample[1:2],mean(df$sample[1:2]),sd(df$sample[1:2]))
# 0.1262907   # last value of pnorm(df$sample[1:3],mean(df$sample[1:3]),sd(df$sample[1:3]))
# 0.4577793    # last value of pnorm(df$sample[1:4],mean(df$sample[1:4]),sd(df$sample[1:4]))
# .
# .
# .

如果我们可以在data.table中做到这一点,那就太好了。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

set.seed(10)
df = data.frame(sample = rnorm(10))

foo <- function(n, x) {
  if (n==1) return(NA)
  xn <- x[1:n]
  tail(pnorm(xn, mean(xn), sd(xn)), 1)
}

sapply(seq(nrow(df)), foo, x=df$sample)

计算方式类似于Calculating cumulative standard deviation by group using R

结果:

#> sapply(seq(nrow(df)), foo, x=df$sample)
# [1]         NA 0.23975006 0.12629071 0.45777934 0.84662051 0.83168998 0.11925118 0.50873996 0.06607348 0.63103339You can put the result in your dataframe:

df$result <- sapply(seq(nrow(df)), foo, x=df$sample)

这是计算的紧凑版本(来自@lmo)

c(NA, sapply(2:10, function(i) tail(pnorm(df$sample[1:i], mean(df$sample[1:i]), sd(df$sample[1:i])), 1)))