看板 R_Language 關於我們 聯絡資訊
[問題類型]: 程式諮詢(我想用R做某件事情,但是我不知道要怎麼用R寫出來) [軟體熟悉度]: 使用者(已經有用R做過不少作品) [問題敘述]: 我想在迴圈中對多個矩陣的某些部分(同樣的行列位置)做取代, 但是我不知道怎麼寫出一般化的code。 我原本想的是在這些矩陣的[1:161, 1]、[162:322, 2]、...、[806:966, 6]放進數列, 但紅色那句顯然行不通,想請教大家有沒有其它的辦法?謝謝! [程式範例]: evaluate <- function(...) {eval(parse(text = paste(..., sep = ".")))} for (k in 1:7) { assign(paste(LETTERS[k], "newdata", sep = "."), matrix(NA, nrow = 966, ncol = 6)) # Generate "A.newdata", "B.newdata", ... ,and "G.newdata" j <- 1 while (j <= ncol(evaluate(LETTERS[k], "newdata"))) { evaluate(emotions[k], "newdata")[1:161+(j-1)*161, j] <- seq(0, 8, 0.05) # length(seq(0, 8, 0.05)) = 161 j <- j + 1 } # The rest of NAs will be substituted with ... # other various values later in this for loop } [環境敘述]: R version 3.3.2 (2016-10-31) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build 7601) Service Pack 1 locale: [1] LC_COLLATE=Chinese (Traditional)_Taiwan.950 [2] LC_CTYPE=Chinese (Traditional)_Taiwan.950 [3] LC_MONETARY=Chinese (Traditional)_Taiwan.950 [4] LC_NUMERIC=C [5] LC_TIME=Chinese (Traditional)_Taiwan.950 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] reshape2_1.4.2 ggplot2_2.2.1 nnet_7.3-12 loaded via a namespace (and not attached): [1] colorspace_1.3-2 scales_0.4.1 magrittr_1.5 assertthat_0.1 [5] lazyeval_0.2.0 plyr_1.8.4 tools_3.3.2 gtable_0.2.0 [9] tibble_1.2 Rcpp_0.12.9 stringi_1.1.2 grid_3.3.2 [13] stringr_1.1.0 munsell_0.4.3 [關鍵字]: 矩陣 取代 迴圈 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.42.156.132 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1486792488.A.690.html
celestialgod: 為什麼要存成A.newdata, B.newdata... ? 02/11 16:15
celestialgod: 存成newdata_list 就好啦 02/11 16:15
celestialgod: 有現成的data structure,請善用 02/11 16:16
celestialgod: 用eval去寫的程式,可讀性很差,很難maintain 02/11 16:16
clsmbstu: 這些newdata是之後要拿來給不同模型predict用的 02/11 20:13
clsmbstu: 我是真的一直沒有善用list... 02/11 20:14