0

I have this data frame. I would like to put each unique Dept and place the corresponding Name under each unique Dept. As you can see there are multiple Dept. For example, final dcoument should look like this:

Internet
    Public-Web
    Intranet
BackOffice
    Batch
    BackEnd
BackEnd
   WebLogic
   Oracle

dput(x)

structure(list(ID = c(1234L, 2345L, 6789L, 3456L, 7890L, 1987L
), Name = structure(c(5L, 3L, 2L, 1L, 6L, 4L), .Label = c("BackEnd", 
"Batch", "Intranet", "Oracle", "Public-Web", "WebLogic"), class = "factor"), 
    Dept = structure(c(3L, 3L, 2L, 2L, 1L, 1L), .Label = c("BackEnd", 
    "BackOffice", "Internet"), class = "factor")), .Names = c("ID", 
"Name", "Dept"), class = "data.frame", row.names = c(NA, -6L))

Any ideas how I would do this in R?

Arun
  • 116,683
  • 26
  • 284
  • 387
user1471980
  • 10,127
  • 48
  • 136
  • 235

2 Answers2

1

You can use split to achieve this:

split(as.character(df$Name), df$Dept)

# $BackEnd
# [1] "WebLogic" "Oracle"  
# 
# $BackOffice
# [1] "Batch"   "BackEnd"
# 
# $Internet
# [1] "Public-Web" "Intranet"  

If you want unique entries, then just do:

df <- unique(df[, 2:3])
split(as.character(df$Name), df$Dept)
Arun
  • 116,683
  • 26
  • 284
  • 387
1

I'll assume you may have duplicates, and therefore use unique:

for(dept in unique(x$Dept)){
  print(dept)
  x2 <- subset(x,subset=Dept==dept)
  for(name in unique(x2$Name)){
    print(paste(sep="","  ",name))
  }
}

Replace the print whith whatever you need.

Julián Urbano
  • 8,378
  • 1
  • 30
  • 52