Create a matrix with another matrix in R

inmierp

So, I have a dataset (usage) that is like the following, in R:

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

And I wanted to convert on a matrix with the usage. I created a matrix where my header is the bikes (bike 1, bike2), and the row names is (item 1, item 2, item 3), and filled with NA and now I want to fill it the usage, such as:

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

I created the following loop:

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

}

But I get this error:

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

Maybe you can try xtabs if you need table

res_tb <- xtabs(Usage~.,df)

such that

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

DATA

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
))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

create a matrix in `R` and each element in that matrix is another matrix

Create new matrix in R by summing rows of another matrix

Subsetting a matrix with another matrix in R

Create a matrix with elements taken by another matrix

R: Map a matrix with another matrix in r

Failed to create matrix in R

R create list or matrix

create a matrix of samples in R

Compare lists within matrix to another matrix in R

sort a matrix based on another matrix in r

How to create covariance matrix in R?

How to create relational matrix in R?

How to create a transition matrix in R

How to create a matrix of lists in R?

How to create a matrix of indices in r?

Split names and create matrix in R

how to create matrix in a list() in R

Create a special diagonal matrix in R

How to create a matrix progressively in R

How to create a confusion matrix in R?

Numpy: Using a matrix as indices for another matrix to create a tensor?

Create a matrix with repetitive values from a slice of another matrix

Is there a fast way to create a bool matrix from another matrix in python?

Programming language R: Create a function. This Function converts one matrix to another matrix such that every odd number are 3 times of that number

How to multiple each row of one matrix with another matrix in R?

R: Subsetting matrix based on another matrix and running rle

Change elements in one matrix based on positions given by another matrix in R

R - change matrix values based on another matrix indices

How to generate a matrix based on a values of another matrix in R