Mean of a column in a data frame, given the column's name

后端 未结 6 759
难免孤独
难免孤独 2020-11-30 01:13

I\'m inside a big function I have to write. In the last part I have to calculate the mean of a column in a data frame. The name of the column I am operating on is given as a

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 01:54

    I think what you are being asked to do (or perhaps asking yourself?) is take a character value which matches the name of a column in a particular dataframe (possibly also given as a character). There are two tricks here. Most people learn to extract columns with the "$" operator and that won't work inside a function if the function is passed a character vecor. If the function is also supposed to accept character argument then you will need to use the get function as well:

     df1 <- data.frame(a=1:10, b=11:20)
     mean_col <- function( dfrm, col ) mean( get(dfrm)[[ col ]] )
     mean_col("df1", "b")
     # [1] 15.5
    

    There is sort of a semantic boundary between ordinary objects like character vectors and language objects like the names of objects. The get function is one of the functions that lets you "promote" character values to language level evaluation. And the "$" function will NOT evaluate its argument in a function, so you need to use"[[". "$" only is useful at the console level and needs to be completely avoided in functions.

提交回复
热议问题