将列添加到数据框,这是前几列 rnorm 的 sd
Add column to dataframe which is the sd of rnorm from previous columns
我有一个两列的数据框
set.seed(120)
df <- data.frame(m1 = runif(500,1,30),n1 = round(runif(500,10,25),0))
我希望添加第三列,使用列 n1
和 m1
生成正态分布,然后获取该正态分布的标准差。我的意思是将 n1
列的每一行中的值用作重复次数 (n),将 m1
用作平均值。
如何编写函数来执行此操作?我尝试使用 apply
stdev <- function(x,y) sd(rnorm(n1,m1))
df$Sim <- apply(df,1,stdev)
但这不起作用。任何指针将不胜感激。
非常感谢,
马特
您的数据框输入如下所示:
# > head(df)
# m1 n1
# 1 12.365323 15
# 2 4.654487 15
# 3 10.993779 24
# 4 24.069388 22
# 5 6.684450 18
# 6 15.056766 16
I mean to use the values in each row of the columns n1 and m1 as the number of replicates (n) and as the mean.
先给大家介绍一下如何使用apply
:
apply(df, 1, function(x) sd(rnorm(n = x[2], mean = x[1])))
但更好的方法是使用 mapply
:
mapply(function(x,y) sd(rnorm(n = x, mean = y)), df$n1, df$m1)
apply
最适合矩阵输入;对于数据框输入,类型转换的开销很大。
另一种选择
lapply(Map(rnorm,n=df$m1,mean=df$n1),sd)
我有一个两列的数据框
set.seed(120)
df <- data.frame(m1 = runif(500,1,30),n1 = round(runif(500,10,25),0))
我希望添加第三列,使用列 n1
和 m1
生成正态分布,然后获取该正态分布的标准差。我的意思是将 n1
列的每一行中的值用作重复次数 (n),将 m1
用作平均值。
如何编写函数来执行此操作?我尝试使用 apply
stdev <- function(x,y) sd(rnorm(n1,m1))
df$Sim <- apply(df,1,stdev)
但这不起作用。任何指针将不胜感激。
非常感谢, 马特
您的数据框输入如下所示:
# > head(df)
# m1 n1
# 1 12.365323 15
# 2 4.654487 15
# 3 10.993779 24
# 4 24.069388 22
# 5 6.684450 18
# 6 15.056766 16
I mean to use the values in each row of the columns n1 and m1 as the number of replicates (n) and as the mean.
先给大家介绍一下如何使用apply
:
apply(df, 1, function(x) sd(rnorm(n = x[2], mean = x[1])))
但更好的方法是使用 mapply
:
mapply(function(x,y) sd(rnorm(n = x, mean = y)), df$n1, df$m1)
apply
最适合矩阵输入;对于数据框输入,类型转换的开销很大。
另一种选择
lapply(Map(rnorm,n=df$m1,mean=df$n1),sd)