Matt Pickard
Matt Pickard

Reputation: 47

In R, iterate over a data.frame by row and get access to the column values

I'm trying to iterate over throws of a data frame and get access to values in the columns of each row. Perhaps, I need a paradigm shift. I've attempted a vectorization approach. My ultimate objective is to use specific column values in each row to filter another data frame.

Any help would be appreciated.

df <- data.frame(a = 1:3, b = letters[24:26], c = 7:9)

f <- function(row) {
  var1 <- row$a
  var2 <- row$b
  var3 <- row$c
}

pmap(df, f)

Is there a way to do this in purrr?

Upvotes: 1

Views: 466

Answers (2)

akrun
akrun

Reputation: 887971

Using pmap, we can do

library(purrr)
pmap(df, ~ f(list(...)))
#[[1]]
#[1] 7

#[[2]]
#[1] 8

#[[3]]
#[1] 9

Or use rowwise with cur_data

library(dplyr)
df %>%
    rowwise %>%
    transmute(new = f(cur_data()))

-output

# A tibble: 3 x 1
# Rowwise: 
#    new
#  <int>
#1     7
#2     8
#3     9

Upvotes: 1

Jakub.Novotny
Jakub.Novotny

Reputation: 3067

library(tidyverse)

df <- data.frame(a = 1:3, b = letters[24:26], c = 7:9)

f <- function(row) {
  var1 <- row$a
  var2 <- row$b
  var3 <- row$c
}



df %>%
  split(rownames(.)) %>%
  map(
    ~f(.x)
  )

Upvotes: 1

Related Questions