【发布时间】:2020-07-21 16:10:03
【问题描述】:
这是我的问题:我有一个函数,它需要 1 个双精度并返回几个双精度,我想直接将它们放在 tibble 的不同列上。我用mutate() 和/或map() 尝试了几种方法。
我不想调用该方法 n 次,并且每次都取函数返回的列表的不同元素。
这是我正在尝试做的一个通用问题:
library(tidyverse)
## a random function that return more than 1 element
f <- function(x){
return(list(x/2,x**2))
}
## a tibble with a column on which I apply the function
tib <- tibble( x = rep(100:120))
tib%>%
mutate(y = f(x))
## error:
#Error : Problem with `mutate()` input `y`.
#x Input `y` can't be recycled to size 21.
#ℹ Input `y` is `f(x)`.
#ℹ Input `y` must be size 21 or 1, not 2.
## what I want to avoid:
tib %>%
mutate(y = f(x)[[1]], z = f(x)[[2]])
我已经为这个问题苦苦挣扎了一段时间。抱歉,如果已经回答了,我在几个论坛上搜索了答案,但一无所获。
提前谢谢你!
【问题讨论】: