Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

dataframe - Extracting different statistics from the same iteration of a for loop in R

I would like to create a data frame between two variables that are linked to the same distribution for each iteration.

sim_df <- rep(NA, 1000)
for (i in 1:1000) { 

#randomly generated distribution
dist = sample(c(0:200), 10, replace = TRUE)
dist = as.data.frame(dist)

#calculated statistics
dist_mean = mean(a[,1])
dist_sd   = sd(a[,1])

#build data frame
df = data.frame(dist_mean, dist_sd)

#return
sim_df = df[i]
}

I am unsure how to define each column so that they can be extracted.

question from:https://stackoverflow.com/questions/65948010/extracting-different-statistics-from-the-same-iteration-of-a-for-loop-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a function which returns mean and sd for one iteration.

return_mean_sd <- function() {
  dist = sample(c(0:200), 10, replace = TRUE)
  c(mean = mean(dist), sd = sd(dist))
}

You can call this function n times to create a dataframe.

set.seed(123)
sim_df <- as.data.frame(t(replicate(100, return_mean_sd())))
head(sim_df)

#   mean   sd
#1 105.0 70.3
#2 119.7 44.3
#3  91.6 56.1
#4  91.5 58.7
#5  99.1 55.2
#6  90.0 52.1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...