简体   繁体   中英

How can I reference a specific variable inside summarise_all, summarise_if, etc?

I want to apply a function to all the columns in a data frame, using another column in the dataframe as an input. For example, imagine I want to take the covariance of every column with a given column, x . Can I do this using summarise_all?

df <- data.frame( x=1:100, y=100:1, z=1)
df %>% summarise( cov.x=cov(x,x), cov.y=cov(y,x), cov.z=cov(z,x) )
    # I want to do this ...
df %>% summarise_all( function(vv) cov(vv,x) )
    # ... using a syntax like this ...

These latter versions give me an error, saying that:

    >> Error in summarise_impl(.data, dots) : 
    >>   Evaluation error: object 'x' not found.

Likewise, this:

df %>% summarise_all( cov(.,x) )

Results in this error:

    >> Error in is.data.frame(y) : object 'x' not found

Help much appreciated

df %>% summarise_all( function(vv) cov(vv,.$x) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM