【发布时间】:2016-03-24 16:15:43
【问题描述】:
我已经为此工作了好几个小时!有人很好地帮助我完成了这个功能——这很有效!
rnormfunc <- function(n.arg, mean.arg, sd.arg, percentdist.arg){ ## main function; first three inputs are for rnorm values, percentdist.arg is percent from mean argument
rnorm1 <- rnorm(n.arg, mean.arg, sd.arg) # creates a vector holding values in normal distrib. from inputs
j <- (percentdist.arg/100) # changes percent distance into decimal value
b <- mean.arg*(1+j) # max percent distance from mean
g <- mean.arg*(1-j) # min percent distance from mean
total.in.range <- sum(rnorm1 >= g & rnorm1 <= b)
return(total.in.range) # sum of number of values within percentage range
}
我需要使用此函数并将以下矩阵/数据框用作参数。我一直在尝试各种方法——基本上是 apply() 系列函数。具体来说,mapply() 或 by() 函数。我正在为是否应该使用矩阵或数据框而苦苦挣扎——以及出于什么原因。
samp.vect <- c(1,1.96,3.92) #three randomized percent distances from mean
r.dat <- matrix(data = NA, nrow = 101, ncol = 4)
colnames(r.dat) <- c("n.arg","mean.arg","sd.arg","percentdist.arg")
r.dat[,1] = seq(from <-1, to <- 100001,by =1000) #1 to 100001 by 1000, first column
r.dat[,2] = 0 # second column is mean, always zero
r.dat[1:50,3] = c(1) # column 3 rows 1 to 50 has sd = 1
r.dat[51:101,3] = c(2) # column 3 rows 51:101 has sd = 2
r.dat[,4] = sample(samp.vect,101, replace = TRUE)
head(r.dat)
tail(r.dat)
产生这个:
> head(r.dat)
n.arg mean.arg sd.arg percentdist.arg
[1,] 1 0 1 3.92
[2,] 1001 0 1 1.00
[3,] 2001 0 1 1.96
[4,] 3001 0 1 1.96
[5,] 4001 0 1 3.92
[6,] 5001 0 1 1.00
所以我被困住了——我觉得我已经挂断了要么使用矩阵,要么使用数据框来启动。我觉得某种类型的 apply(rnormfunc, r.dat$n.arg, r.dat$n.mean...) 可能是一种方式,但我不知道该怎么做。
然后操作这些数据结构之一,其中四列中的每一列都需要按行用作上述 rnormfunc() 的参数。然后我想使用 cbind() 将它附加到矩阵/数据框。
不得不说,这非常令人沮丧,但同时正确学习和学习非常有趣!另外,请随时批评我的礼仪/帖子,以便更容易获得反馈!
【问题讨论】:
标签: r