看板 R_Language 關於我們 聯絡資訊
[問題類型]: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來) [軟體熟悉度]: 新手(沒寫過程式,R 是我的第一次) [問題敘述]: 基本學習 [程式範例]: 我有參考此網頁的寫法,不過也出現錯誤 https://sites.google.com/site/rlearningsite/manage/manage4 在coursera學習R,之前有自己找文件看, 第一週的考試最後3題不太會,都是篩選資料後計算的 資料如下 https://www.sendspace.com/file/vtlml8 Ozone Solar.R Wind Temp Month Day 1 41 190 7.4 67 5 1 2 36 118 8.0 72 5 2 3 12 149 12.6 74 5 3 4 18 313 11.5 62 5 4 5 NA NA 14.3 56 5 5 6 28 NA 14.9 66 5 6 第17題是要選 Ozne>31和 Temp>90的資料,再做計算 我打程式碼如下: hw1.Q18<-hw1[Ozone>31, Temp>90] 錯誤訊息如下: Error in `[.data.frame`(hw1, Ozone > 31, Temp > 90) : object 'Temp' not found 要怎麼修改才能篩選出我要的資料呢? [關鍵字]: 篩選 選擇性,也許未來有用 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 120.127.235.145 ※ 文章網址: http://www.ptt.cc/bbs/R_Language/M.1415848834.A.746.html
rockken: 你有打 attach(hw1) ?? 11/13 12:23
andrew43: hw1.Q18 <- subset(hw1, Ozone > 31 & Temp > 90) 11/13 12:29
andrew43: 這樣可能比較好懂。 11/13 12:30
criky: 謝謝andrew43, 我好像也打過類似的code orz 結果不行 11/13 14:16
criky: 空格有關係嗎? 11/13 14:16
criky: 選第1欄的資料是 hw1[,1] , 可以用欄位名稱 Ozone寫嗎? 11/13 14:31
criky: 請教rockken板友,若有匯入資料,但沒打attach會不一樣嗎? 11/13 14:40
bxxl: 要attch才能直接使用column名當變數,不然就要用xxx$yyy這樣 11/13 17:18
obarisk: with比較好,attach在變數多時... 11/13 19:34
Edster: # 使用欄位名稱呼叫. 適用 data.frame & matrix 11/13 21:54
Edster: x = data.frame(x1 = c(1:10,NA), x2 = c(NA,1:10)) 11/13 21:55
Edster: y = x[,"x1"] > 5 & x[,"x2"] > 3 11/13 21:55
Edster: x[y & !is.na(y),] 11/13 21:55
Edster: 你的例子裡面有 NA, 所以最後篩選的時候, 要用 is.na 11/13 21:56
Edster: 可以使用欄位名稱呼叫該欄數列, 這沒問題. 11/13 21:58
Edster: 哎呀, 太久沒用 subset. 果然還是andrew版友厲害. 11/13 22:00
Edster: 但我有問題. 因為我平常習慣讓需要呼叫的欄位可自由設定. 11/13 22:02
Edster: 例如 x[,"x1"] 如此我可以在寫 function 的時候. 11/13 22:02
Edster: 利用變數替代 "x1". 但使用 subset 就不行了. 11/13 22:03
Edster: 比如 subset(x, "x1" > 5) 跟 subset(x, x1 >5) 11/13 22:06
Edster: 就不一樣.. 11/13 22:11
criky: 謝謝各位回應,我有用 is.na作答~ 希望愈來愈上手 11/13 22:31
Wush978: For Edster最後面關於subset和x1的問題的解答 11/14 00:27
gsuper: Q18<-hw1[hwl[,"Ozone"]>31 & hwl[,"Temp"]>90,] 11/14 00:35