Re: [問題] list問題
※ 引述《aa955260 (aa955260)》之銘言:
: [問題類型]:
: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來)
: [軟體熟悉度]:
: 入門(寫過其他程式,只是對語法不熟悉)
: [問題敘述]:
: 各位大大好,我的資料集內有多個人(sub.list),每個人下面有3種不同狀態(stat.list)
: ,每種狀態下有3種不同的狀況(level.list),目前我是用for-loop來分別讀取2維的
: data.frame(A, B, C),我想做的是用Scal.list將3種不同level.list的資料與名稱包起
: 來,再用All.list把3種不同stat.list的資料與名稱包起來,做成1個大的All.list。以
: 下為錯誤範例,請問我該怎麼修改會比較好呢?或是有沒有其他更好的寫法呢?
: 感謝
: [程式範例]:
: sub.list <- list("001", "002", "003")
: stat.list <- list("High", "Low", "None")
: level.list <- list("Light", "Moderate", "Vigorous")
: Scal.list <- list()
: All.list <- list()
: for(i in 1:length(sub.list)){
: for(j in 1:length(stat.list)){
: A_path <- paste0(data.path, sub.list[i], "\\", stat.list[j]
: ,"\\", level.list[1], ".csv")
: A <- fread(A_path, header = T)
: B_path <- paste0(data.path, sub.list[i], "\\", stat.list[j]
: , "\\", level.list[2], ".csv")
: B <- fread(B_path , header = T)
: C_path <- paste0(data.path, sub.list[i], "\\", stat.list[j]
: , "\\", level.list[3], ".csv")
: C <- fread(C_path, header = T)
: t.list <- list()
: t.list <- list(A, B, C)
: names(t.list)[1] <- level.list[1]
: names(t.list)[2] <- level.list[2]
: names(t.list)[3] <- level.list[3]
: Scal.list[[length(Scal.list)+1]] <- t.list
: }
: All.list[[length(All.list)+1]] <- Scal.list
: }
: [環境敘述]:
: R version 3.3.2 (2016-10-31)
: Platform: x86_64-w64-mingw32/x64 (64-bit)
: Running under: Windows >= 8 x64 (build 9200)
: locale:
: [1] LC_COLLATE=Chinese (Traditional)_Taiwan.950 LC_CTYPE=Chinese
: (Traditional)_Taiwan.950
: [3] LC_MONETARY=Chinese (Traditional)_Taiwan.950 LC_NUMERIC=C
: [5] LC_TIME=Chinese (Traditional)_Taiwan.950
: attached base packages:
: [1] stats graphics grDevices utils datasets methods base
: loaded via a namespace (and not attached):
: [1] tools_3.3.2
: [關鍵字]:
:
: 多層list、多層迴圈讀檔
:
library(data.table)
subVec <- c("001", "002", "003")
statVec <- c("High", "Low", "None")
levelVec <- c("Light", "Moderate", "Vigorous")
# data.frame做法
DF <- expand.grid(sub = subVec, stat = statVec, level = levelVec)
DF <- transform(DF, path = paste0(dataPath, "/", sub, "/", stat,
"/", level, ".csv"))
# data.table做法
DT <- CJ(sub = subVec, stat = statVec, level = levelVec)
DT[ , path := paste0(dataPath, "/", sub, "/", stat, "/", level, ".csv")]
# 讀檔
sapply(DT$path, fread, header = TRUE)
--
R資料整理套件系列文:
magrittr #1LhSWhpH (R_Language) https://goo.gl/72l1m9
data.table #1LhW7Tvj (R_Language) https://goo.gl/PZa6Ue
dplyr(上.下) #1LhpJCfB,#1Lhw8b-s (R_Language) https://goo.gl/I5xX9b
tidyr #1Liqls1R (R_Language) https://goo.gl/i7yzAz
pipeR #1NXESRm5 (R_Language) https://goo.gl/zRUISx
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.38.133.116
※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1484217423.A.5B8.html
討論串 (同標題文章)
R_Language 近期熱門文章
PTT數位生活區 即時熱門文章