使用purrr进行行操作

问题描述

我希望使用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)

解决方法

不确定您的预期输出是什么,但是您可以使用{ "public_id": "eneivicys42bq5f2jpn2","version": 1570979139,"signature": "abcdefghijklmnopqrstuvwxyz12345","width": 1000,"height": 672,"format": "jpg","resource_type": "image","created_at": "2017-08-11T12:24:32Z","tags": [],"bytes": 350749,"type": "upload","etag": "5297bd123ad4ddad723483c176e35f6e","url": "http://res.cloudinary.com/demo/image/upload/v1570979139/eneivicys42bq5f2jpn2.jpg","secure_url": "https://res.cloudinary.com/demo/image/upload/v1570979139/eneivicys42bq5f2jpn2.jpg","original_filename": "sample","eager": [ { "transformation": "c_pad,h_300,w_400","width": 400,"height": 300,"url": "http://res.cloudinary.com/demo/image/upload/c_pad,w_400/v1570979139/eneivicys42bq5f2jpn2.jpg","secure_url": "https://res.cloudinary.com/demo/image/upload/c_pad,w_400/v1570979139/eneivicys42bq5f2jpn2.jpg" },执行按行操作。但是,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