我是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 ...
答案 0 :(得分:1)
我不确定这是否正是您正在寻找的(我非常确定我用于采样的值不是您想要的),但以下代码细分可以将数据放入您正在寻找的格式中。
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