Re: [問題] data frame撈取資料-複雜條件

看板R_Language作者 (天)時間9年前 (2016/04/07 02:46), 9年前編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《aee36900 (持久戰!!)》之銘言: : [問題敘述]: : : 延續上個data frame 撈取特定資料問題,但是條件比較複雜 : 我需要c1 c2條件下的c3作為篩選條件 : 程式我嘗試用下面的方式敘述 : 但是沒有效果@@ : 想請問哪邊需要修改 : : [程式範例]: : : df <- df[df$c3 %in% df[df$c1 >= '0.xxx' & df$c2 == 1,c3],] : : [關鍵字]: : : data frame select condition row column 好讀版:http://pastebin.com/nY3KvCmd # 資料生成 set.seed(500) dat <- data.frame(c1 = rnorm(10), c2 = sample(1:3, 10, TRUE), c3 = sample(LETTERS[1:5], 10, TRUE)) # c1 c2 c3 # 1 0.96848929 1 A # 2 1.96536781 3 A # 3 0.88632253 1 D # 4 0.03054026 2 A # 5 0.94955742 1 B # 6 -0.57673001 3 E # 7 0.72152335 3 E # 8 0.61909890 3 A # 9 0.02100582 1 E # 10 0.27485018 1 A # 推文前兩行說的方法 dat[dat$c3 %in% dat[dat$c1 >= 0.9 & dat$c2 == 1, 'c3'], ] # c1 c2 c3 # 1 0.96848929 1 A # 2 1.96536781 3 A # 4 0.03054026 2 A # 5 0.94955742 1 B # 8 0.61909890 3 A # 10 0.27485018 1 A # 推文補充的dplyr方法 library(dplyr) dat %>% filter(c3 %in% (dat %>% filter(c1 >= 0.9, c2 == 1) %>% .$c3)) # c1 c2 c3 # 1 0.96848929 1 A # 2 1.96536781 3 A # 3 0.03054026 2 A # 4 0.94955742 1 B # 5 0.61909890 3 A # 6 0.27485018 1 A -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.73.231 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1459968410.A.D57.html ※ 編輯: celestialgod (140.109.73.231), 04/07/2016 02:47:30

04/07 10:36, , 1F
感謝c大,自己一直驗證錯誤因為沒注意C2的內容
04/07 10:36, 1F
文章代碼(AID): #1N1LcQrN (R_Language)
文章代碼(AID): #1N1LcQrN (R_Language)