[R] Pivot Table "like" structure

David Winsemius dwinsemius at comcast.net
Tue Oct 16 18:22:35 CEST 2012


On Oct 13, 2012, at 5:38 PM, Bhupendrasinh Thakre wrote:

> HI Team,
>
> I am currently working on problem and stumped on "for" loop.
>
> Data:
>
> structure(list(Coutry = structure(c(3L, 3L, 3L, 3L, 2L, 2L, 1L,
> 1L), .Label = c("J", "M", "U"), class = "factor"), State =  
> structure(c(1L,
> 1L, 4L, 2L, 5L, 5L, 3L, 6L), .Label = c("A", "C", "K", "O", "S",
> "T"), class = "factor"), City = structure(c(1L, 8L, 7L, 2L, 3L,
> 6L, 5L, 4L), .Label = c("BEN", "HRD", "JKL", "KK", "KL", "KMM",
> "OKC", "TYU"), class = "factor"), Char1 = structure(c(1L, 2L,
> 1L, 3L, 4L, 2L, 3L, 5L), .Label = c("A", "B", "C", "D", "M"), class  
> = "factor"),
>    Char2 = structure(c(1L, 2L, 1L, 2L, 3L, 4L, 4L, 2L), .Label =  
> c("ABCD",
>    "EFGH", "FGHJ", "GGGG"), class = "factor"), Char3 = structure(c(1L,
>    1L, 2L, 3L, 1L, 1L, 2L, 3L), .Label = c("ASDFG", "DDDDD",
>    "EEEEEE"), class = "factor")), .Names = c("Coutry", "State",
> "City", "Char1", "Char2", "Char3"), row.names = c(NA, -8L), class =  
> "data.frame")
>
> Question:
>
> I am trying to create a pivot table which will count the occurrences  
> of Char1 : Char4
> from the columns Coutry, State, City. I am not sure to use all the  
> four columns and get something like
>
> structure(list(Group.1 = structure(1:4, .Label = c("ABCD", "EFGH",
> "FGHJ", "GGGG"), class = "factor"), x = c(2L, 3L, 1L, 2L)), .Names =  
> c("Group.1",
> "x"), row.names = c(NA, -4L), class = "data.frame")
>
> Code which I tried to use with not best results:
>
> aggregate(State, list(Char2), FUN="count")

You are apparently using attach() on your dataframe. That will often  
create confusion. Better to use with():

?with

For your problem without `attach` these are available:

 > table(dat$Char2)

ABCD EFGH FGHJ GGGG
    2    3    1    2


 > aggregate(dat$Char2, dat['Char2'], length)
   Char2 x
1  ABCD 2
2  EFGH 3
3  FGHJ 1
4  GGGG 2

With attach() in effect for your dataframe this would have worked as  
well:

 > aggregate(Char2, list(Char2), length)
   Group.1 x
1    ABCD 2
2    EFGH 3
3    FGHJ 1
4    GGGG 2

'count' is not a base R function, although it may be available in some  
packages. If you have other packages you are loading, you should name  
them.

If you want to get tabulations of all the columns that have "Char" in  
their names

 > sapply(dat[ grep("Char", names(dat)) ], table)
$Char1

A B C D M
2 2 2 1 1

$Char2

ABCD EFGH FGHJ GGGG
    2    3    1    2

$Char3

  ASDFG  DDDDD EEEEEE
      4      2      2

-- 

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list