我有一个矢量:
chbin <- seq (from = 0, to = 10, by = 0.02)
我还有另外两个向量,每个向量都有45个值。
chmean
cherr
我需要创建一个数据帧。
数据框的每一行应具有45个值,其中第一个值为dnorm(chbin, mean = (chmean[1]), sd = (cherr[1], log=FALSE)
,第二个值为dnorm(chbin, mean = (chmean[2]), sd = (cherr[2], log=FALSE)
,依此类推至dnorm(chbin, mean = (chmean[45]), sd = (cherr[45], log=FALSE)
。即,对于chbin中的每个值,dnorm被计算45次,对于chmean中的每个值和cherr中的对应值计算一次。
结果数据帧将具有45列和与chbin中的值相同的行数。
答案 0 :(得分:1)
您可以使用以下嵌套for循环:
chbin <- seq (from = 0, to = 10, by = 0.02)
chmean <- seq (from = 1, to = 2, by = 0.02)
cherr <- seq (from = 1, to = 2, by = 0.02)
foo <- data.frame(matrix(0, nrow=length(chbin), ncol=length(chmean)) )
for(i in 1:length(chbin) ){
for(j in 1:length(chmean) ){
foo[i,j] <- dnorm(chbin[i], mean = chmean[j], sd = cherr[j], log=FALSE)
}
}
答案 1 :(得分:1)
mapply
可用于解决问题:
chbin <- seq(from = 0, to = 10, by = 0.02)
chmean <- seq(from = 1, to = 2, by = 0.02)
cherr <- seq(from = 1, to = 2, by = 0.02)
foo <- mapply(function(mean,sd) dnorm(chbin,mean,sd), mean=chmean, sd=cherr)