iT邦幫忙

0

R語言詢問問題

r
  • 分享至 

  • xImage

產生以下矩陣且命名為mat3:

m= matrix(1:20,5,4)
dimnames(m) <- list(c("stat1","stat2","stat3","stat4","stat5"),c("num1","num2","text","num3"))
m[, 1] <- c(3,5,1,9,2)
m[, 2] <- c(20,80,40,10,70)
m[, 3] <- c("k2","k5","k1","k3","k4")
m[, 4] <- c(800,200,900,400,600)

print(m)
1.依據text欄產生將k1~k5由小到大順序排列的新矩陣(其相對的其他欄位值都要一起變動),且命名為mat3.text
2.依據num3欄產生將200~900由小到大順序排列的新矩陣(其相對的其他欄位值都要一起變動),且命名為mat3.num3

obarisk iT邦研究生 1 級 ‧ 2022-03-29 09:58:30 檢舉
這題目不好。matrix 中的資料的型別都要相同
放了字串,整個 matrix 都會變字串
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2022-03-28 15:11:54

如果你以後還會來問問題的話
https://ithelp.ithome.com.tw/upload/images/20220328/20001787Fu77MFVPSD.png

https://ithelp.ithome.com.tw/upload/images/20220328/20001787I4OelzkoSk.png

0
may031556
iT邦新手 5 級 ‧ 2022-04-01 13:52:27
> m= matrix(1:20,5,4)
> dimnames(m) <- list(c("stat1","stat2","stat3","stat4","stat5"),c("num1","num2","text","num3"))
> m[, 1] <- c(3,5,1,9,2)
> m[, 2] <- c(20,80,40,10,70)
> m[, 3] <- c("k2","k5","k1","k3","k4")
> m[, 4] <- c(800,200,900,400,600)
> 
> print(m)
      num1 num2 text num3 
stat1 "3"  "20" "k2" "800"
stat2 "5"  "80" "k5" "200"
stat3 "1"  "40" "k1" "900"
stat4 "9"  "10" "k3" "400"
stat5 "2"  "70" "k4" "600"
> 
> # 產生以上矩陣且命名為mat3
> mat3 = m
> 
> # 依據text欄產生將k1~k5由小到大順序排列的新矩陣(其相對的其他欄位值都要一起變動),且命名為mat3.text
> mat3.text = m[order(m[,"text"]),]
> print(mat3.text)
      num1 num2 text num3 
stat3 "1"  "40" "k1" "900"
stat1 "3"  "20" "k2" "800"
stat4 "9"  "10" "k3" "400"
stat5 "2"  "70" "k4" "600"
stat2 "5"  "80" "k5" "200"
> 
> 
> # 依據num3欄產生將200~900由小到大順序排列的新矩陣(其相對的其他欄位值都要一起變動),且命名為mat3.num3
> mat3.num3 = m[order(m[,"num3"]),]
> print(mat3.num3)
      num1 num2 text num3 
stat2 "5"  "80" "k5" "200"
stat4 "9"  "10" "k3" "400"
stat5 "2"  "70" "k4" "600"
stat1 "3"  "20" "k2" "800"
stat3 "1"  "40" "k1" "900"

我要發表回答

立即登入回答