假設我有一個矩陣,5乘以5的水果名稱(5類水果)。我想在這個現有矩陣中添加5個新列,並在每行中添加單個水果的總數,最後再添加一行以顯示每種同類水果的總和。數據矩陣是這樣的,如何在數據矩陣中添加與新列相同的字符串的總數與R
[,1] [,2] [,3] [,4] [,5]
[1,]mango banana mango
[2,]apple kiwi banana
[3,] mango
[4,]mango apple
[5,] orange
我想輸出(數據幀)這樣,
[,1] [,2] [,3] [,4] [,5] [apple] [banana] [kiwi] [mango] [orange]
[1,]mango banana mango 0 1 0 2 0
[2,]apple kiwi banana 1 1 1 0 0
[3,] mango 0 0 0 1 0
[4,]mango apple 1 0 0 1 0
[5,] orange 0 0 0 0 1
[6,] 2 2 1 4 1
我已經試過grep
,它是整個矩陣分解成列向量。我實際上並不知道如何用R完成整個數據矩陣。這裏是代碼,
fruits <- matrix(c("mango", "", "banana", "", "mango", "apple", "kiwi", "", "banana", "","", "", "mango", "", "", "mango", "", "apple", "", "", "", "", "", "orange", ""), nrow = 5, ncol = 5, byrow = TRUE)
fruits$apple <- length(grep("apple", fruits[1:nrow(fruits), 1:ncol(fruits)]))
fruits$banana <- length(grep("banana", fruits[1:nrow(fruits), 1:ncol(fruits)]))
fruits$kiwi <- length(grep("kiwi", fruits[1:nrow(fruits), 1:ncol(fruits)]))
fruits$mango <- length(grep("mango", fruits[1:nrow(fruits), 1:ncol(fruits)]))
fruits$orange <- length(grep("orange", fruits[1:nrow(fruits), 1:ncol(fruits)]))
請幫忙。
您不能在矩陣中混合不同的數據類型。也許你應該使用數據框。 – Stibu
感謝您的糾正 –