Sum in a Cross Table

I am new in R. Apologies if the questions is too silly.

I have a sample input data table as follows.

Column-1 Column-2 Column-3 
 FF       FF       2
 NN       NN       5
 FF       FF       2
 NN       NN       1
 FN       FF       3

Output should be

       FF   FN  NF  NN
    FF  4   0   0   0
    FN  3   0   0   0
    NF  0   0   0   0
    NN  0   0   0   6

I have used table() function, but it only gives "count", and not "sum". Appreciate any help!

Answers


With the little known xtabs function. Your data:

l <- c("FF", "FN", "NF", "NN")

data <- data.frame(
   Column1 = factor(c("FF", "NN", "FF", "NN", "FN"), levels = l),
   Column2 = factor(c("FF", "NN", "FF", "NN", "FF"), levels = l),
   Column3 = c(2, 5, 2, 1, 3))

xtabs(Column3 ~ ., data)
#        Column2
# Column1 FF FN NF NN
#      FF  4  0  0  0
#      FN  3  0  0  0
#      NF  0  0  0  0
#      NN  0  0  0  6

The output is a table but you can wrap it into as.matrix to get a matrix.


Need Your Help

Oracle Hierarchical query: with two node attributes NodeId and NodeType

oracle11g hierarchical-data recursive-query

I have the following use case where I want to make use of hierarchical queries to get the desired result.

Query to conditionally calculate data against previous record

mysql

Please excuse if the title is not descriptive enough.