What does the dplyr period character “.” reference?

前端 未结 2 438
死守一世寂寞
死守一世寂寞 2020-11-27 17:05

What does the period . reference in the following dplyr code?:

(df <- as.data.frame(matrix(rep(1:5, 5), ncol=5)))
#    V1 V2 V3 V4 V5
#  1  1         


        
2条回答
  •  孤城傲影
    2020-11-27 17:30

    The dot has a special meaning within funs. In that context it refers to the dummy parameter. See ?funs for a descrption.

    funs constructs a "fun_list" class object which represents a list of functions. Each argument of funs is a function name, character string representing a function name or an expression representing the body of the function. In the last case, within the expression representing the function body, the argument of the function is represented by dot so that . == 5 refers to the function function(.) . == 5 (although dplyr does not actually construct that function but rather uses a "fun_list" object instead).

    In this example, mutate_each will run the function once for each column so that this does the same thing as in the question except it also prints out the input each time the constructed function (it is not actually constructed but we can think about it that way) is called:

    > out <- mutate_each(df, funs({print(.); . == 5}))
    [1] 1 2 3 4 5
    [1] 1 2 3 4 5
    [1] 1 2 3 4 5
    [1] 1 2 3 4 5
    [1] 1 2 3 4 5
    

    In your filter example, funs is not being used and filter does not work with "fun_list" objects anyways.

    dot has other meanings within other contexts within dplyr and can have other meanings within other contexts for other packages as well.

提交回复
热议问题