【问题标题】:Manipulate data.frame with function使用函数操作 data.frame
【发布时间】:2016-05-26 19:59:21
【问题描述】:

我有以下数据框:

DF2 <- data.frame(column = c("C1", "C2", "C3", "C4", "C5"), 
              start = c(2005,2001,2006,2005,2009), 
              end = c(2012,2009,2011,2010,2012), 
              stringsAsFactors = F)

并希望创建一个执行以下操作的函数:

year.calcs <- function(x) {
          pre.5 <- x$start - 5
          pre.1 <- x$start - 1
          post.5 <- x$end + 5
          post.1 <- x$end + 1
}

所以我可以打电话:

year.calcs(DF2)

并将所有新列添加到数据框中。

【问题讨论】:

  • 只需在最后一行下方添加cbind(x, pre.5, pre.1, post.5, post.1)

标签: r function data-manipulation


【解决方案1】:

这是另一种方法:

year.calcs <- function(x) {
  x[["pre.5"]] <- x$start - 5
  x[["pre.1"]] <- x$start - 1
  x[["post.5"]] <- x$end + 5
  x[["post.1"]] <- x$end + 1

  x
}

df <- year.calcs(x=DF2)

返回

> df
  column start  end pre.5 pre.1 post.5 post.1
1     C1  2005 2012  2000  2004   2017   2013
2     C2  2001 2009  1996  2000   2014   2010
3     C3  2006 2011  2001  2005   2016   2012
4     C4  2005 2010  2000  2004   2015   2011
5     C5  2009 2012  2004  2008   2017   2013

【讨论】:

    猜你喜欢
    • 2016-11-20
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2018-08-04
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多