假设我有一个 5 x 5 的矩阵,带有水果名称(5 类水果)。我想在这个现有矩阵中添加 5 个新列,每行中的单个水果的总数,最后一个额外的行来显示每种相同水果的总和。数据矩阵是这样的,
[,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)]))
请帮忙。