I'm looking to use purrr for a rowwise operation where each element is used in the function as a string. 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. However, pmap
passes each row as a vector and not as dataframe so $
will not work. 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 :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.