1

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'
0

3 Answers 3

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

Data:

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

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

One option is acast from reshape2

library(reshape2)
acast(df,  Item ~ Bike, fill = 0)
#       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
))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.