繁体   English   中英

使用 purrr 进行 rowwise 操作

[英]Using purrr for rowwise operations

我希望使用 purrr 进行行操作,其中每个元素在函数中用作字符串。 我得到的错误是它不能将 $ 归因于原子向量。 下面是一个例子:

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)

不确定您的预期输出是什么,但您可以使用pmap执行逐行操作。 但是, pmap将每一行作为向量而不是数据帧传递,因此$将不起作用。 您可以将函数更改为:

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)
}

您可以将pmap用作:

iris %>% mutate(data = pmap(select(., matches('Sepal|Petal')), 
               ~test_function(c(...)))) -> tmp

每行数据都是该行数据的一个小标题。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM