【问题标题】:processing data frame in R在R中处理数据帧
【发布时间】:2013-03-29 05:20:40
【问题描述】:

我有这个数据框。我想把每个唯一的 Dept 放在每个唯一的 Dept 下,并在每个唯一的 Dept 下放置相应的 Name。如您所见,有多个 Dept。例如,final dcoument 应如下所示:

Internet
    Public-Web
    Intranet
BackOffice
    Batch
    BackEnd
BackEnd
   WebLogic
   Oracle

输入(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))

任何想法我将如何在 R 中做到这一点?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我假设你可能有重复,因此使用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))
      }
    }
    

    用你需要的任何东西替换print

    【讨论】:

      【解决方案2】:

      您可以使用split 来实现:

      split(as.character(df$Name), df$Dept)
      
      # $BackEnd
      # [1] "WebLogic" "Oracle"  
      # 
      # $BackOffice
      # [1] "Batch"   "BackEnd"
      # 
      # $Internet
      # [1] "Public-Web" "Intranet"  
      

      如果你想要唯一的条目,那么就这样做:

      df <- unique(df[, 2:3])
      split(as.character(df$Name), df$Dept)
      

      【讨论】:

      • 我需要使用两个 for 循环。对于每个唯一的部门,我需要列出名称。在第二个循环中,我将在 Name 下进行更多处理。
      • 我不明白你的评论。 Arun answer 比两个循环快得多。
      • 我猜他只是不知道如何在split之后进行迭代
      • 你的意思是他对“存储”这个变量不感兴趣,而只是打印?
      • 类似的东西,是的。我的猜测,无论如何
      猜你喜欢
      • 2015-05-16
      • 2015-07-01
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 2018-08-30
      • 2012-11-14
      相关资源
      最近更新 更多