r - 条件赋值框架$col <- val with magrittr

标签 r variable-assignment magrittr

根据 Iris$Petal.Length 分配 Iris$column 的 Magrittr 语法是什么?没有 Magrittr 的示例:

df      <- iris[47:56,]
df$val1 <- NA                                           ## create column
df$val1[which(df$Petal.Length < 1.52)]                         <- "cake"
df$val1[which(df$Petal.Length > 1.55 & df$Petal.Length <=4.55)] <- "pie"
df$val1[which(df$Petal.Length > 4.55)]                        <- "apple"

head(df)

这会导致:

Petal.Length Petal.Width  Species    val1

1.6                0.2     setosa     pie

1.4                0.2     setosa     cake

1.5                0.2     setosa     cake

1.4                0.2     setosa     cake

1.4                1.4.  versicolor   apple

最佳答案

与您编写的内容完全等效的 magrittr 语法是:

df %>% transform(val1 = NA) %$%
  inset(.,Petal.Length < 1.52,"val1","cake") %$%
  inset(.,Petal.Length > 1.55 & Petal.Length <= 4.55,"val1","pie") %$%
  inset(.,Petal.Length > 4.55,"val1","apple")

或者对 magrittr 的别名非常热心:

df %>% transform(val1 = NA) %$%
  inset(.,Petal.Length %>% is_less_than(1.52),"val1","cake") %$%
  inset(.,Petal.Length %>% is_greater_than(1.55) & Petal.Length %>% 
  is_weakly_less_than(4.55),"val1","pie") %$%
  inset(.,Petal.Length %>% is_greater_than(4.55),"val1","apple")

还有一个变体:

df %>% transform(val1 = NA) %$%
  inset(.,Petal.Length %>% is_less_than(1.52),"val1","cake") %$%
  inset(.,Petal.Length %>% {is_greater_than(.,1.55) & is_weakly_less_than(.,4.55)},"val1","pie") %$%
  inset(.,Petal.Length %>% is_greater_than(4.55),"val1","apple")

前两个与基础中的严格等效(管道除外!):

df %>% transform(val1 = NA) %$%
  `[<-`(.,Petal.Length < 1.52,"val1","cake") %$%
  `[<-`(.,Petal.Length > 1.55 & Petal.Length <= 4.55,"val1","pie") %$%
  `[<-`(.,Petal.Length > 4.55,"val1","apple")

该变体相当于:

df %>% transform(val1 = NA) %$%
  `[<-`(.,Petal.Length < 1.52,"val1","cake") %$%
  `[<-`(.,Petal.Length %>% {`>`(.,1.55) & `<=`(.,4.55)},"val1","pie") %$%
  `[<-`(.,Petal.Length > 4.55,"val1","apple")

我使用 transform 因为它是一个 base 函数,而 mutate 是一个 dplyr 函数,但它们的工作原理相同就到这里。

有关所有别名的定义,请参阅:?extract

关于r - 条件赋值框架$col <- val with magrittr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45266079/

相关文章:

r - 如何更改 R 华夫饼图中 "tile grout"的颜色以匹配背景

c++ - 从另一个程序分配一个特定的内存地址,并改变它的值(value)

javascript - 这在 JavaScript 中意味着什么?

r - 管道中命名空间调用的函数的运算符优先级

r - 'pipe' 、 'dot' 和 'dollar' 运算符的串联似乎在 R 中起作用?

r - 在不使用 'for' 构造的情况下创建列表列表的任何更简洁/优雅的方法?

r - glmer 警告 : parameters or bounds appear to have different scalings

r - 使用 ggplot2 在世界地图中绘制子区域

class - 在Groovy中分配对象属性的简便方法?

r - 操作顺序总结