我是R的新手,我想通过将脚本拼接在一起来解决问题,但未能针对以下问题提出解决方案。
我想做的是在以下脚本中运行for循环100次,并将每个结果并排显示在数据框/表/矩阵的新列中,理想情况下保持1列不变并将所有新运行合并到其中。
这是我正在运行的脚本:
# Test data.
data <- data.frame(a=2, b=3, c=4)
# Sampling from first row of data.
row <- 1
N_samples <- 50
samples <- sample(1:ncol(data), N_samples, rep=TRUE, prob=data[row,])
site_sample=data[row,]
# Count the number of each entry and store in a list.
for (i in 1:ncol(data)){
site_sample[[i]] <- sum(samples==i)
}
# Unlist the data to get an array that represents the bootstrap row.
site_sample <- unlist(site_sample)
write.table(site_sample, file="test1.csv", sep = ",")
谢谢你的帮助。
我正在尝试获得如下所示的内容:
a 9 15 21 ...(100 columns)
b 15 16 19 ...
c 26 19 10 ...
我不确定这是否正是您要寻找的(我很确定我用于采样的值不是您想要的),但是以下代码段可以将数据放入您想要的格式正在寻找。
data <- data.frame(a=2, b=3, c=4) # Test data
row <- 1
N_samples <- 50
newDF <- data.frame(names(data), row.names = 1) # Creates new, empty dataframe
for (i in 1:ncol(data)) {
# Not sure if the next line is what you want, but it works as a good demo
samples <- sample(1:ncol(data), N_samples, rep=TRUE, prob=data[row,])
# Adds the count of the values generated above as the next col in the dataframe
newDF <- cbind(newDF, as.vector(table(samples)))
}
colnames(newDF) <- rep(" ", ncol(newDF)) # Removes dataframe's column names
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句