【问题标题】:Improve repetitive code - R tables改进重复代码 - R 表
【发布时间】:2017-11-10 10:14:19
【问题描述】:
table1 <- matrix(c(51,43,22,92,28,21,68,22,9,12),ncol=2,byrow=TRUE)
table2 <- matrix(c(31,72,55,94,24,21,6,22,9,12),ncol=2,byrow=TRUE)
table3 <- matrix(c(55,7,22,33,21,111,64,221,92,10),ncol=2,byrow=TRUE)

结构相同的三个表。

我想对上面的所有表格进行相同的数据操作。

rownames(table1) <- c("x", "y", "z", "v", "p")
table1 <- table1[!rownames(table1) %in% c("z", "p"), ]

上面我已经重命名了行,然后根据 table1 的字符串将它们删除。

而不是对所有三个表重复上面的代码,我怎样才能一次对所有表进行这种操作?

谢谢

【问题讨论】:

  • 知道的可以做个函数!
  • 顺便说一句,命名这些行有什么意义?

标签: r dataframe matrix refactoring


【解决方案1】:

更容易。使用lapply,这样您就不必编写三遍函数了。

table1 <- matrix(c(51,43,22,92,28,21,68,22,9,12),ncol=2,byrow=TRUE)
table2 <- matrix(c(31,72,55,94,24,21,6,22,9,12),ncol=2,byrow=TRUE)
table3 <- matrix(c(55,7,22,33,21,111,64,221,92,10),ncol=2,byrow=TRUE)

#function 
tablemodification<-function(yourtable){
  rownames(yourtable) <- c("x", "y", "z", "v", "p")
  yourtable <- yourtable[!rownames(yourtable) %in% c("z", "p"), ]
}

lapply(list(table1, table2, table3), tablemodification)

【讨论】:

    【解决方案2】:

    具有可重复使用的功能!

       table1 <- matrix(c(51,43,22,92,28,21,68,22,9,12),ncol=2,byrow=TRUE)
    table2 <- matrix(c(31,72,55,94,24,21,6,22,9,12),ncol=2,byrow=TRUE)
    table3 <- matrix(c(55,7,22,33,21,111,64,221,92,10),ncol=2,byrow=TRUE)
    
    do_this <- function(table) {
      rownames(table) <- c("x", "y", "z", "v", "p")
      return(table[!rownames(table) %in% c("z", "p"), ])
    }
    
    table1 <- do_this(table1)
    table2 <- do_this(table2)
    table3 <- do_this(table3)
        > 
        > table3
          [,1] [,2]
        x   55    7
        y   22   33
        v   64  221
        > 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 2013-10-12
      • 2019-01-21
      相关资源
      最近更新 更多