我正在尝试使用“类似管道”的运算符创建一个新变量,它基于 LETTERS
向量与数据帧中的其他变量长度相同。出了点问题,我对 magrittr
还太陌生,无法诊断问题。
当我尝试使用一些“传统的”嵌套函数时,我能够正确地创建变量:
expand.grid(a=c(1000-500,1000,1000+500),
b=c(15,150)) %>%
mutate(c=paste("foo", LETTERS[seq_along(a)],sep="_"))
## a b c
## 1 500 15 foo_A
## 2 1000 15 foo_B
## 3 1500 15 foo_C
## 4 500 150 foo_D
## 5 1000 150 foo_E
## 6 1500 150 foo_F
然后我想我会尝试使用 magrittr
和 dplyr
%>%
expand.grid(a=c(1000-500,1000,1000+500),
b=c(15,150)) %>%
mutate(c=paste("foo", a %>%
seq_along %>%
LETTERS[.],sep="_"))
## Error: incorrect number of dimensions
当我从 magrittr
添加别名提取 ([
) 函数时,这也不起作用:
expand.grid(a=c(1000-500,1000,1000+500),
b=c(15,150)) %>%
mutate(c=paste("foo", a %>%
seq_along %>%
extract(LETTERS,.),
sep="_"))
## Error: incorrect number of dimensions
我已经尝试使用 debug_pipe
调试管道,但无济于事。如果有任何想法,我将不胜感激!
最佳答案
如果你愿意,你可以:
expand.grid(a=1000+c(-500, 0, 500), b=c(15,150)) %>%
mutate(c = a %>% seq_along %>% LETTERS[.] %>% paste0("foo_", .))
关于r - 使用 transform 和 %>% 创建新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23715699/