[英]Using purrr for rowwise operations
I'm looking to use purrr for a rowwise operation where each element is used in the function as a string.我希望使用 purrr 进行行操作,其中每个元素在函数中用作字符串。 The error I'm getting is that it can't attribute an $ to an atomic vector.我得到的错误是它不能将 $ 归因于原子向量。 Here's an example:下面是一个例子:
test_function = function(dat_) {
petal_width = dat_$Petal.Width
sepal_width = dat_$Sepal.Width
petal_length = dat_$Petal.Length
sepal_length = dat_$Sepal.Length
list(petal_length,sepal_length,sepal_width,petal_width) %>%
bind_cols -> test
return(test)
}
apply(iris, 1, test_function)
Not sure what your expected output is but you can use pmap
to perform row-wise operations.不确定您的预期输出是什么,但您可以使用pmap
执行逐行操作。 However, pmap
passes each row as a vector and not as dataframe so $
will not work.但是, pmap
将每一行作为向量而不是数据帧传递,因此$
将不起作用。 You can change the function to :您可以将函数更改为:
library(tidyverse)
test_function = function(dat_) {
petal_width = dat_[['Petal.Width']]
sepal_width = dat_[['Sepal.Width']]
petal_length = dat_[['Petal.Length']]
sepal_length = dat_[['Sepal.Length']]
tibble(a = petal_length,b = sepal_length,
c = sepal_width,d = petal_width) -> test
return(test)
}
You can use pmap
as :您可以将pmap
用作:
iris %>% mutate(data = pmap(select(., matches('Sepal|Petal')),
~test_function(c(...)))) -> tmp
Each row of data is a tibble with data from that row.每行数据都是该行数据的一个小标题。
tmp$data[[1]]
# A tibble: 1 x 4
a b c d
<dbl> <dbl> <dbl> <dbl>
1 1.4 5.1 3.5 0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.