整洁的条件替换

时间:2018-03-12 15:18:33

标签: r dplyr tidyverse

是否有更多整洁的方式来实现以下目标?

d = data_frame(domain = c('http:news.com/', 'http:news.com/', 'http:news.com/'),
               url = c('http:cnn.com/article/123', 'politics', 'economics'))

d %>% mutate(url = {
  f = !str_detect(url, '^http'); # filter
  replace(url, f, paste0(domain[f], url[f]))
})
# A tibble: 3 x 2
  domain         url                     
  <chr>          <chr>                   
1 http:news.com/ http:cnn.com/article/123
2 http:news.com/ http:news.com/politics  
3 http:news.com/ http:news.com/economics 

2 个答案:

答案 0 :(得分:1)

执行case_when

可能更容易
d %>% mutate(url = case_when(
  !str_detect(url, '^http') ~ paste0(domain, url), 
  TRUE~url))

或只是if_else

d %>% mutate(url = if_else(!str_detect(url, '^http'), 
  paste0(domain, url), 
  url))

答案 1 :(得分:0)

基础R中的整洁方式:

idx <- !grepl('^http', d$url)
d$url[idx] <- do.call(paste0, d[idx,])

给出:

> d
# A tibble: 3 x 2
  domain         url                     
  <chr>          <chr>                   
1 http:news.com/ http:cnn.com/article/123
2 http:news.com/ http:news.com/politics  
3 http:news.com/ http:news.com/economics