从数据帧的各列获取参数,输出到列表,然后绑定到数据帧

时间:2015-12-18 01:56:41

标签: r

我一直在努力工作几个小时!有人很友好地帮助我一起工作!

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

所以我被卡住了 - 我觉得我已经挂了使用矩阵或数据帧来启动。我感觉某种类型的应用(rnormfunc,r.dat $ n.arg,r.dat $ n.mean ......)可能是方式,但我不知道该怎么做。

然后操作其中一个数据结构,其中四列中的每一列都需要用作上述rnormfunc()的参数。然后我想使用cbind()将它附加到矩阵/数据框架。

要说,这是令人难以置信的令人沮丧,但同时正确和学习是非常有趣的!另外,请随意批评我的礼仪/帖子,以便更容易反馈!

1 个答案:

答案 0 :(得分:0)

我只在前6个案例(行)中对此进行了测试,但这应该是可推广的:

apply( head(r.dat), 1, function(x) 
            rnormfunc( x['n.arg'], x['mean.arg'], x['sd.arg'], x['percentdist.arg']) )