Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reshape: cast oddity

Tags:

r

Either it's late, or I've found a bug, or cast doesn't like colnames with "." in them. This all happens inside a function, but it "doesn't work" outside of a function as much as it doesn't work inside of it.

x <- structure(list(df.q6 = structure(c(1L, 1L, 1L, 11L, 11L, 9L, 
4L, 11L, 1L, 1L, 2L, 2L, 11L, 5L, 4L, 9L, 4L, 4L, 1L, 9L, 4L, 
10L, 1L, 11L, 9L), .Label = c("a", "b", "c", "d", "e", "f", "g", 
"h", "i", "j", "k"), class = "factor"), df.s5 = structure(c(4L, 
4L, 1L, 2L, 4L, 4L, 4L, 3L, 4L, 1L, 2L, 1L, 2L, 4L, 1L, 3L, 4L, 
2L, 2L, 4L, 4L, 4L, 2L, 2L, 1L), .Label = c("a", "b", "c", "d", 
"e"), class = "factor")), .Names = c("df.q6", "df.s5"), row.names = c(NA, 
25L), class = "data.frame")

cast(x, df.q6 + df.s5 ~., length)

No worky.

However, if:

colnames(x) <- c("variable", "value")
cast(x, variable + value ~., length)

Works like a charm.

like image 778
Brandon Bertelsen Avatar asked Feb 26 '26 19:02

Brandon Bertelsen


1 Answers

For me I use a similar solution to what Spacedman points out.

#take your data.frame x with it's two columns

#add a column
x$value <- 1

#apply your cast verbatim
cast(x, df.q6 + df.s5 ~., length)

   df.q6 df.s5 (all)
1      a     a     2
2      a     b     2
3      a     d     3
4      b     a     1
5      b     b     1
6      d     a     1
7      d     b     1
8      d     d     3
9      e     d     1
10     i     a     1
11     i     c     1
12     i     d     2
13     j     d     1
14     k     b     3
15     k     c     1
16     k     d     1

Hopefully that helps!

Jay

like image 122
Jay Avatar answered Mar 01 '26 08:03

Jay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!