对数据框使用 rnorm

Using rnorm for a dataframe

我想在具有例如 nrow=11451 个元素的数据帧上使用 rnorm 函数。我不知道如何编写代码以对导致具有 nsim 列和 nrow 行的 sim-dataframe 的每一行应用 rnorm。

dfsim <- rnorm (n=nsim, mean=df[[?]], sd=df[[?]])

例如:

> head(df)
An object of class "SpatialLinesDataFrame"
Slot "data":
           LINEARID            FULLNAME RTTYP MTFCC          M01         SD01 Nsim
10969 1104486135650       US Hwy 90 Alt     U S1200 0.0009886878 0.0001253361   10
10970 1104486135651       US Hwy 90 Alt     U S1200 0.0009831224 0.0001442643   10
10416 1102965182224 Southwest Fwy E Acc     M S1640 0.0010000000 0.0000000000   10
10494 1103342335512   Robin Hood Ct Pvt     M S1780 0.0010000000 0.0000000000   10
10493 1103342334514 Little John Way Pvt     M S1750 0.0010000000 0.0000000000   10
1847  1101842210421      Arrowood Cir N     M S1400 0.0010000000 0.0000000000   10

我的预期结果是每行多十列,包括模拟值。

我使用了下面的代码但是得到了 "invalid argument error"

> dfnorm <- apply(df@data, 1, function(x) rnorm(x["Nsim"], mean=x["M01"], sd=x["SD01"]))
 Error in rnorm(x["Nsim"], mean = x["M01"], sd = x["SD01"]) : 
  invalid arguments 

由于dataframe太大,我使用subset函数只保留三行,保存到.rdata文件中。这是 link: df.rdata

在您的数据框中,您需要添加一列样本大小,如下所示:

 dataFrameApply <- data.frame(sampleSize = c(100,100,100),               
                            meanNum = c(1,2,3), sdNum = c(1,2,3))
      sampleSize meanNum sdNum
1        100       1     1
2        100       2     2
3        100       3     3

然后使用 apply 遍历每一行。第二个参数可以是 1 或 2,具体取决于是应用于行还是列。

normalize <- apply(dataFrameApply, 1, function(x) rnorm(x[1], mean=x[2], sd=x[3]))

这在我的机器上对我有用

dfDataFrame  <- as.data.frame(df@data)
dataFrameSub <- dfDataFrame[,c(7,5,6)]
normalize    <- apply(dataFrameSub,    1, function(x) rnorm(x[1], mean=x[2], 
                sd=x[3]))

可以从 purrr 包中执行 pmap 并将 rnorms 直接构建到您的数据框中:

library(tidyverse)
df@data <- df@data %>% 
  mutate(rnorms = pmap(list(Nsim, M01, SD01), function(n, mu, sd) rnorm(n, mu, sd)),
         rnorms = map_chr(rnorms, ~ paste(., collapse = " "))) %>% 
  bind_cols(., read.table(text = .$rnorms, sep = " ")) %>%
  select(-rnorms)