使用R中的管道(带有%>%
),如何从函数的输出中传递特定于的向量元素来馈送下一个函数的参数?
我尝试使用点运算符将大括号(即.[1], .[2]
)中的位置无效。
对我来说唯一有效的方法是使用sapply()
,但我想知道是否还有更简单的解决方案。
#I have a vector containing a sequence of numbers, with some duplicates and gaps,
#and I want to use its start and end points to create an analogous consecutive sequence.
original_sequence <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 98, 98, 99, 100, 101,
102, 103, 104, 105, 106, 107, 108, 109, 110)
## unsuccessful attempt #1
original_sequence %>%
range() %>%
seq()
[1] 1 2 ## this result is equivalent to the output of `seq(2)`,
## but what I want is to compute `seq(1 ,110)`.
## unsuccessful attempt #2
original_sequence %>%
range() %>%
seq(.[1]), .[2])
Error: unexpected ',' in:
" range() %>%
seq(.[1]),"
## attempt #3: somewhat successful but I wonder whether there's a better way
original_sequence %>%
range() %>%
sapply(., seq)
[[1]]
[1] 1
[[2]]
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
[39] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
[77] 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
底线-我能够用sapply
做到这一点,但我希望本着第二次尝试的精神找出解决方案,因为知道一种通用的方法来挑选具体的方法更为方便您要传递给下一个函数的参数的向量元素。
答案 0 :(得分:1)
一种方法是使用{}
并将输入参数传递给seq
library(dplyr)
original_sequence %>%
range() %>%
{seq(.[[1]], .[2])}
#[1] 1 2 3 4 5 6 7 8 9 10 11 12......
或者我们可以将其与基数R do.call
original_sequence %>% range() %>% {do.call(seq, as.list(.))}
或者如@ Ozan147所述,如果您的序列始终以1开头,我们可以使用max
original_sequence %>% max %>% seq
答案 1 :(得分:0)
我们可以使用reduce
library(tidyverse)
original_sequence %>%
range %>%
reduce(seq)
#[1] 1 2 3 4 ...