Fill values in a matrix from column 4 based on a value in column 3 for all categories in column 1 and column 2 in R

Dataframe df is the given dataframe and we want to obtain the matrix below for value in VAR3 as “101”. Use of xtabs() does not produce the desired output. The value inside 2X2 matrix is the value in VAR4.

df <- data.frame(
  VAR1 = c(1,1,1,1,1,1,2,2,2,2,2,2),
  VAR2 = c(10,10,10,20,20,20,10,10,10,20,20,20),
  VAR3 = c(101,102,103,104,105,106,101,102,103,104,105,106),
  VAR4 = c(58,20,27,200,23,36,108,800,56,72,27,235)
)

Desired output:

enter image description here

  • 2

    Working backwards from your desired result, maybe xtabs(VAR4 ~ VAR1 + VAR2, df, subset = VAR3 %in% c(101, 104)). Not clear as you don’t mention needing to subset on 104, just 101.

    – 

Leave a Comment