简体   繁体   English

在 R 中,逐行迭代 data.frame 并访问列值

[英]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 ?有没有办法在purrr中做到这一点?

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

Using pmap , we can do使用pmap ,我们可以做

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

#[[2]]
#[1] 8

#[[3]]
#[1] 9

Or use rowwise with cur_data或者将rowwisecur_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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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