有一些類似這個問題,但我仍然無法解決我的特殊問題。我有一個函數可以從df中獲取行的隨機樣本。使用dplyr庫。重複一個功能並保存結果。 R
rohis <- function(dat, ind, n) {
ind <- enquo(ind)
dat %>%
filter(UQ(ind) %in% sample(unique(UQ(ind)), n)) %>%
slice(sample(row_number()))
}
現在我想重複此功能的10倍,並將結果保存在一個列表:
lst <- list()
for (i in 1:10){
i = rohis(data, ind, 3)
lst[[length(lst) + 1]] = i
}
但是得到這個錯誤:
Error in lst[[length(lst) + 1]] <- i :
object of type 'closure' is not subsettable
這裏有一些數據:
data <- structure(list(pos1 = c(5, 15, 25, 40, 80, 5, 18, 22, 38, 84,
5, 16, 50, 92, 31, 50, 20, 30, 50, 70, 27, 50, 60, 50, 90, 20,
40, 54, 65, 78, 7, 17, 27, 42, 85, 10, 19, 25, 39, 88, 10, 19,
55, 93, 32, 54, 22, 35, 52, 72, 29, 55, 65, 55, 95, 22, 46, 57,
67, 79), pos2 = c(10, 17, 30, 42, 90, 10, 20, 24, 42, 87, 10,
19, 52, 100, 40, 70, 25, 32, 60, 90, 30, 60, 71, 60, 100, 25,
50, 50, 69, 90, 19, 27, 39, 49, 99, 20, 29, 30, 49, 92, 20, 29,
59, 100, 48, 76, 30, 39, 67, 98, 36, 68, 76, 65, 100, 30, 55,
55, 70, 100), chr = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1,
1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1,
1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2), ind = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L), .Label = c("A", "B", "C", "D", "E", "F"), class ="factor")), .Names = c("pos1", "pos2", "chr", "ind"), row.names = c(NA, -60L), class = "data.frame")
通常我會建議你使用'lapply(REP(3,10),函數(x)rohis(data,ind,x))' – 5th
我也認爲你不能只是循環一個空的列表。 R中的列表非常靈活,但我認爲R中的對象總是需要一些價值。當我上一次瀏覽列表時(意思是在我[發現'lapply']之前(https://www.datacamp.com/community/tutorials/r-tutorial-apply-family)),我設置了我的列表,例如'lst = list(1:3,1:2)',並用'lst [[i]]調用它'' – 5th
什麼是'ind'?沒有定義。此外,你的循環迭代'i',然後在循環中改變它的值!你應該做'j = rohis(...)'。另外,你的'data'有一個縮進問題,它的最後一部分是不可讀的。你能否從行首開始刪除空白? –