[問題] dataframe使用ifelse將符合條件的print出

看板R_Language作者 (rebecca_caca)時間8年前 (2017/12/19 00:45), 8年前編輯推噓0(008)
留言8則, 5人參與, 8年前最新討論串1/1
[問題類型]: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來) [軟體熟悉度]: 入門(寫過其他程式,只是對語法不熟悉) [問題敘述]: 請簡略描述你所要做的事情,或是這個程式的目的 想只用ifelse函式將data frame 裡符合資料的印出 [程式範例]: 張貼能夠重現錯誤的程式碼,可以幫助版友更快的幫你解決問題 house = read.csv('D:/house.csv',header=TRUE,stringsAsFactors=FALSE) head(house) str(house) a=house$price if(a>5000){ print(a) } [環境敘述]: R-3.4.2 執行結果如下: house = read.csv('D:/house.csv',header=TRUE,stringsAsFactors=FALSE) > head(house) price unit_price measure parking parking_price floor floor2 nfloor area 1 545 35.86 15.20 0 0.0 5 25 5 A4 2 1568 41.42 37.86 0 0.0 6 36 12 A4 3 2100 34.80 53.20 1 16.9 2 4 11 A5 4 926 28.10 33.00 0 0.0 5 25 5 A11 5 1050 35.50 29.60 0 0.0 2 4 6 A11 6 750 42.47 17.66 0 0.0 2 4 3 A9 room hall bath house_age date house_type season 1 1 2 1 26.9 9903 公寓 Q1 2 3 2 2 5.9 9907 大樓 Q3 3 3 2 2 9.3 9907 大樓 Q3 4 3 2 2 26.2 9812 公寓 Q4 5 3 2 2 10.5 9902 大樓 Q1 6 2 2 1 36.7 9906 公寓 Q2 > str(house) 'data.frame': 2931 obs. of 16 variables: $ price : int 545 1568 2100 926 1050 750 1180 1416 4110 1295 ... $ unit_price : num 35.9 41.4 34.8 28.1 35.5 ... $ measure : num 15.2 37.9 53.2 33 29.6 ... $ parking : int 0 0 1 0 0 0 0 0 1 0 ... $ parking_price: num 0 0 16.9 0 0 ... $ floor : int 5 6 2 5 2 2 2 14 9 3 ... $ floor2 : int 25 36 4 25 4 4 4 196 81 9 ... $ nfloor : int 5 12 11 5 6 3 3 16 14 5 ... $ area : chr "A4" "A4" "A5" "A11" ... $ room : int 1 3 3 3 3 2 2 3 2 2 ... $ hall : int 2 2 2 2 2 2 2 2 2 2 ... $ bath : num 1 2 2 2 2 1 1 2 2 1 ... $ house_age : num 26.9 5.9 9.3 26.2 10.5 36.7 35.5 11.2 3.9 26.5 ... $ date : int 9903 9907 9907 9812 9902 9906 9907 9905 9907 9811 ... $ house_type : chr "公寓" "大樓" "大樓" "公寓" ... $ season : chr "Q1 " "Q3 " "Q3 " "Q4 " ... > a=house$price > if(a>5000){ + print(a) + } Warning message: In if (a > 5000) { : 條件的長度 > 1,因此只能用其第一元素 > 謝謝大家~~ [關鍵字]: 選擇性,也許未來有用 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.78.42 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1513615523.A.845.html ※ 編輯: melodyheyhey (223.136.63.202), 12/19/2017 00:50:45

12/19 01:23, 8年前 , 1F
print(a[a>5000])
12/19 01:23, 1F

12/19 09:05, 8年前 , 2F
像是 house[house$price > 5000, ]
12/19 09:05, 2F

12/19 09:21, 8年前 , 3F
謝謝你們~可是有要求要用ifelse條件式印出的話要
12/19 09:21, 3F

12/19 09:21, 8年前 , 4F
怎麼寫呢?
12/19 09:21, 4F

12/19 10:16, 8年前 , 5F
sapply(a,function(x){ if(x>5000) print (x) })
12/19 10:16, 5F

12/19 10:39, 8年前 , 6F
ifelse 跟 print 感覺不太搭 @@
12/19 10:39, 6F

12/19 10:40, 8年前 , 7F
print(ifelse(a>5000,a,""),quote=F)
12/19 10:40, 7F

12/19 10:40, 8年前 , 8F
print.table(na.omit(ifelse(a>5000,a,NA)))
12/19 10:40, 8F
文章代碼(AID): #1QD_2ZX5 (R_Language)
文章代碼(AID): #1QD_2ZX5 (R_Language)