How to add a column in the data frame within a function

后端 未结 2 1900
礼貌的吻别
礼貌的吻别 2020-12-11 02:47

I have a data frame, and I want to do some calculation with existing columns and create new column in my data set which is a combination of existing... I can do this easily

2条回答
  •  暖寄归人
    2020-12-11 02:58

    the best approach is to use mutate() from dplyr library. Example:

    addcol = function(dat){
        dat1 = mutate(dat, x2=x1*2)
        return(dat1)
    }
    

    dat is a data frame with a column named "x1". Use this function addcol(), the new dataset now has a new column named "x2" which is twice the value of "x1", assuming x1 is numeric.

提交回复
热议问题