用R中的另一个矩阵创建一个矩阵

时间:2020-03-23 15:12:47

标签: r matrix

因此,我在R中有一个类似于以下内容的数据集(用法):

Item    Bike    Usage
item1   bike1   1
item2   bike1   2
item1   bike2   1
item3   bike2   2

我想用用法转换成矩阵。 我创建了一个矩阵,其中标题为自行车(自行车1,bike2),行名称为(项目1,项目2,项目3),并用NA填充,现在我想用它来填充用法,例如:

bike1  bike2
item 1 1      1
item 2 1      0
item 3 0      1

我创建了以下循环:

for (i in 1:nrow(usage)) {
  item<-usage[i,1]
  bike<-usage[i,2]
  matriz[item,bike]<-usage[i,3]

matriz[is.na(matriz)]<-0

}

但是我得到这个错误:

Error in `[<-`(`*tmp*`, item, bike, value = list(Usage = 6)) : 
  invalid subscript type 'list'

3 个答案:

答案 0 :(得分:1)

library(tidyr)
pivot_wider(dat, "Item", names_from="Bike",
            values_from="Usage", values_fill=list(Usage=0))
# # A tibble: 3 x 3
#   Item  bike1 bike2
#   <chr> <int> <int>
# 1 item1     1     1
# 2 item2     2     0
# 3 item3     0     2

数据:

dat <- structure(list(Item = c("item1", "item2", "item1", "item3"), 
    Bike = c("bike1", "bike1", "bike2", "bike2"), Usage = c(1L, 
    2L, 1L, 2L)), class = "data.frame", row.names = c(NA, -4L
))

答案 1 :(得分:0)

如果您需要餐桌,也许可以尝试xtabs

res_tb <- xtabs(Usage~.,df)

这样

> res_tb
       Bike
Item    bike1 bike2
  item1     1     1
  item2     2     0
  item3     0     2

数据

df <- structure(list(Item = c("item1", "item2", "item1", "item3"), 
    Bike = c("bike1", "bike1", "bike2", "bike2"), Usage = c(1L, 
    2L, 1L, 2L)), class = "data.frame", row.names = c(NA, -4L
))

答案 2 :(得分:0)

一个选项是acast中的reshape2

library(reshape2)
acast(df,  Item ~ Bike, fill = 0)
#       bike1 bike2
#item1     1     1
#item2     2     0
#item3     0     2

数据

df <- structure(list(Item = c("item1", "item2", "item1", "item3"), 
    Bike = c("bike1", "bike1", "bike2", "bike2"), Usage = c(1L, 
    2L, 1L, 2L)), class = "data.frame", row.names = c(NA, -4L
))