creating a column with replaced values using mutate and dplyr

前端 未结 1 856
我在风中等你
我在风中等你 2021-01-27 13:55

This likely a duplicate somewhere on stackoverflow and is a followup question to dplyr mutate replace dynamic variable name.

Now I am trying to use a variable name as th

相关标签:
1条回答
  • 2021-01-27 14:35

    Rather than replace mpg's existing hwy variable I did the following to illustrate the same thing and put it into context:

    From your previous question:

    library(dplyr)
    library(ggplot2)
    library(lazyeval)
    
    data(mpg)
    
    # "normal" dplyr
    a <- mpg %>% mutate(hwybin=replace(hwy>25,1,0))
    
    
    # varying just the RHS
    varname <- "hwy"
    b <- mpg %>% mutate_(hwybin=interp(~replace(varname>25, 1 ,0),
                                       varname=as.name(varname)))
    
    identical(a, b)
    

    For this particular question:

    # varying both RHS and LHS
    
    colname <- "hwybin"
    z <- mpg %>% mutate_(.dots=setNames(list(interp(~replace(varname>25, 1 ,0),
                                varname=as.name(varname))), colname))
    
    # tests
    identical(a, z)
    identical(b, z)
    
    0 讨论(0)
提交回复
热议问题