dplyr在数据子集上

时间:2018-05-31 10:37:31

标签: r dplyr

假设以下数据框

foo = c(1, 2, 3) 
bar = c("AA", "AB", "AC")
other = c("Z","N","Z")
df = data.frame(foo,bar,other,stringsAsFactors=FALSE)

我有一个运行多行的dplyr转换,其中一个我只想使用数据子集。

换句话说,从

开始
 df%>%
      mutate(other=replace(other, foo > 1, "New"))

是否可以在dplyr

中转换以下代码
df[df$foo<3,]$bar<-sub("A", "B", df[df$foo<3,]$bar)

这样的事情

mutate(df$foo<3=sub("A", "B", df$foo<3, perl = TRUE))

2 个答案:

答案 0 :(得分:0)

这是一个整合的解决方案:

library(tidyverse)
df  %>%
  mutate(other=replace(other, foo > 1, "New"),
         bar= ifelse(foo<3,sub("A", "B", bar),bar))

#   foo bar other
# 1   1  BA     Z
# 2   2  BB   New
# 3   3  AC   New

答案 1 :(得分:0)

我知道这个问题与dplyr有关,但我data.table语法类似于您尝试使用mutate

library(data.table)
setDT(df)

df[foo > 1, other := 'New']
df[foo < 3, bar := sub('A', 'B', bar)]
df

#    foo bar other
# 1:   1  BA     Z
# 2:   2  BB   New
# 3:   3  AC   New

#With pipes
df %>% 
  .[foo > 1, other := 'New'] %>% 
  .[foo < 3, bar := sub('A', 'B', bar)]