当前位置: 动力学知识库 > 问答 > 编程问答 >

r - Manipulate data.frame with function

问题描述:

I have the following dataframe:

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)

and would like to create a function that does the following:

year.calcs <- function(x) {

pre.5 <- x$start - 5

pre.1 <- x$start - 1

post.5 <- x$end + 5

post.1 <- x$end + 1

}

so I could call:

year.calcs(DF2)

and add all of the new columns to the dataframe.

网友答案:

Here is another method:

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)

Which returns

> 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
分享给朋友:
您可能感兴趣的文章:
随机阅读: