Data table in R with 3 columns

How to transform a dataset with 3 columns like:

 V1   V2   V3
 X    AB   6 
 X    EF   5
 Y    CD   7 
 Z    EF   8
 A    JK   9
 B    LM   10
 B    JK   6

      

To:

  AB CD EF JK LM
X 6  0  5  0  0
Y 0  7  0  0  0
Z 0  0  8  0  0 
A 0  0  0  9  0
B 0  0  0  6  10

      

+3


source to share


2 answers


you can use

library(reshape2)
dcast(df, V1~V2, fill=0, value.var="V3")
##   V1 AB CD EF JK LM
## 1  A  0  0  0  9  0
## 2  B  0  0  0  6 10
## 3  X  6  0  5  0  0
## 4  Y  0  7  0  0  0
## 5  Z  0  0  8  0  0

      



Or to use a matrix

 acast(df, V1~V2, value.var='V3', fill=0)

      

+2


source


According to @akrun's suggestion, you can use the R base:

xtabs(V3~V1+V2, df)

      

What gives:

#   V2
#V1  AB CD EF JK LM
#  A  0  0  0  9  0
#  B  0  0  0  6 10
#  X  6  0  5  0  0
#  Y  0  7  0  0  0
#  Z  0  0  8  0  0

      

Or using tidyr

library(tidyr)
spread(df, V2, V3, fill = 0)

      



What gives:

#  V1 AB CD EF JK LM
#1  A  0  0  0  9  0
#2  B  0  0  0  6 10
#3  X  6  0  5  0  0
#4  Y  0  7  0  0  0
#5  Z  0  0  8  0  0

      


<strong> data

structure(list(V1 = structure(c(3L, 3L, 4L, 5L, 1L, 2L, 2L), .Label = c("A", 
"B", "X", "Y", "Z"), class = "factor"), V2 = structure(c(1L, 
3L, 2L, 3L, 4L, 5L, 4L), .Label = c("AB", "CD", "EF", "JK", "LM"
), class = "factor"), V3 = c(6L, 5L, 7L, 8L, 9L, 10L, 6L)), .Names = c("V1", 
"V2", "V3"), class = "data.frame", row.names = c(NA, -7L))

      

+2


source







All Articles