如何在同一个代码块中使用dplyr的rename和mutate动词。

huangapple go评论50阅读模式
英文:

How to use dplyr verbs rename and mutate in a same chunk

问题

我想首先将我的 x 变量重命名为 newX,然后基于 newXy 的值来创建一个新列名为 z。将重命名和变异放在同一个块中会导致错误。
有没有一种方法可以在不出错的情况下使用选项1?

set.seed(1)
dat <- data.frame(
  x = sample(c(0,1), size = 5, replace = TRUE),
  y = sample(c(0,1), size = 5, replace = TRUE)
)
# 选项1
dat %>%
  rename(newX = x) %>%
  mutate(z = rowSums(dat[c("newX", "y")] == 1))

# 选项2
dat <- dat %>%
  rename(newX = x)
dat %>% 
  mutate(z = rowSums(dat[c("newX", "y")] == 1))

请注意,我只翻译了您提供的代码部分,没有其他内容。

英文:

I want to first rename my x variable to newX and then mutate a new column name z based on values of newX and y. Putting rename and mutate in same chunk result in an error.
Is there a way to use option 1 without an error?

set.seed(1)
dat &lt;- data.frame(
  x = sample(c(0,1), size = 5, replace = TRUE),
  y = sample(c(0,1), size = 5, replace = TRUE)
)
 # option 1
dat %&gt;%
  rename(newX = x) %&gt;%
  mutate(z = rowSums(dat[c(&quot;newX&quot;, &quot;y&quot;)] == 1))

 # option 2
dat &lt;- dat %&gt;%
  rename(newX = x)
dat %&gt;% 
  mutate(z = rowSums(dat[c(&quot;newX&quot;, &quot;y&quot;)] == 1))

答案1

得分: 2

使用 dplyr::pick(),它允许您从当前数据框环境中“挑选”变量,而不是 dat[c("vars")],它在任何转换之前引用了 dat 对象。

library(dplyr)

dat %>%
  rename(newX = x) %>%
  mutate(z = rowSums(pick(newX, y) == 1))
  newX y z
1    0 0 0
2    1 0 1
3    0 0 0
4    0 1 1
5    1 1 2
英文:

Use dplyr::pick(), which lets you “pick” variables from the current dataframe environment, rather than dat[c(&quot;vars&quot;)], which references the dat object before any transformations.

library(dplyr)

dat %&gt;%
  rename(newX = x) %&gt;%
  mutate(z = rowSums(pick(newX, y) == 1))
  newX y z
1    0 0 0
2    1 0 1
3    0 0 0
4    0 1 1
5    1 1 2

huangapple
  • 本文由 发表于 2023年6月2日 10:49:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定