Chris
Chris

Reputation: 2256

How cast on text?

This is probably a very trivial question... I have a table similar to this:

tbl1 <- data.frame(rbind(
c("N1","G1","a"),
c("N1","G1","b"),
c("N1","G2","d"),
c("N2","G1","e"),
c("N2","G1","f"),
c("N2","G2","g")
))

Which I want to convert it to this:

X1 | G1         | G2

N1 | c("a","b") | "d"

N2 | c("e","f") | "g"

I'm thinking this is the direction to go, but what should the "?" be set to?

tbl2 <- data.frame(cast(tbl1,X1~X2, value="X3", ? ))

Thanks for all contributions to [r] at Stack Overflow!

/Chris

Upvotes: 0

Views: 310

Answers (2)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162341

This actually does what you are asking for, although the printed version of the results looks a little odd at first sight. (The difficulty in printing it nicely, of course, is that this is a data.frame in which some "cells" are vectors with more than one element).

Especially if you need this for the information it contains (rather than for the printed object it produces), it could still serve your purposes just fine:

tbl2 <- with(tbl1, 
            tapply(as.character(X3), 
                   INDEX = list(X1, X2), 
                   FUN = I))
# Equivalently:    FUN = function(X) X))

# Examine the resulting data.frame
tbl2
#    G1          G2 
# N1 Character,2 "d"
# N2 Character,2 "g"

# Extract particular elements
tbl2[["N1", "G1"]]
# [1] "a" "b"

tbl2[["N2", "G2"]]
# [1] "g"

Upvotes: 3

Ramnath
Ramnath

Reputation: 55695

Another solution

library(reshape2)
dcast(tbl1, X1 ~ X2, fun.aggregate= function(x) paste(x, collapse = ","))

Upvotes: 4

Related Questions