简体   繁体   中英

dplyr 0.8.0 mutate_at: use of custom function without overwriting original columns

Using the new grammar in dplyr 0.8.0 using list() instead of funs(), I want to be able to create new variables from mutate_at() without overwriting the old. Basically, I need to replace any integers over a value with NA in several columns, without overwriting the columns.

I had this working already using a previous version of dplyr, but I want to accommodate the changes in dplyr so my code doesn't break later.

Say I have a tibble:

x <- tibble(id = 1:10, x = sample(1:10, 10, replace = TRUE), 
            y = sample(1:10, 10, replace = TRUE))

I want to be able to replace any values above 5 with NA. I used to do it this way, and this result is exactly what I want:

x %>% mutate_at(vars(x, y), funs(RC = replace(., which(. > 5), NA)))
# A tibble: 10 x 5
      id     x     y  x_RC  y_RC
   <int> <int> <int> <int> <int>
 1     1     2     3     2     3
 2     2     2     1     2     1
 3     3     3     4     3     4
 4     4     4     4     4     4
 5     5     2     9     2    NA
 6     6     6     8    NA    NA
 7     7    10     2    NA     2
 8     8     1     3     1     3
 9     9    10     1    NA     1
10    10     1     8     1    NA

This what I've tried, but it doesn't work:

x %>% mutate_at(vars(x, y), list(RC = replace(., which(. > 5), NA)))

Error in [<-.data.frame ( *tmp* , list, value = NA) : new columns would leave holes after existing columns

This works, but replaces the original variables:

x %>% mutate_at(vars(x, y), list(~replace(., which(. > 5), NA)))
# A tibble: 10 x 3
      id     x     y
   <int> <int> <int>
 1     1     2     3
 2     2     2     1
 3     3     3     4
 4     4     4     4
 5     5     2    NA
 6     6    NA    NA
 7     7    NA     2
 8     8     1     3
 9     9    NA     1
10    10     1    NA

Any help is appreciated!

几乎在那里,只需创建一个命名列表。

x %>% mutate_at(vars(x, y), list(RC = ~replace(., which(. > 5), NA)))

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