purrr - 提取数据帧的行作为向量

时间:2018-06-07 01:11:27

标签: r tidyverse purrr

我有一个数据框,希望将每一行提取到一个列表中 作为矢量强迫。我只想使用tidyversepurrr 包来实现这一点。

我有以下reprex我试图这样做:


library(magrittr)
library(tidyverse)
# Create the raw dummy data frame
df <- data.frame(
    x = c("apple", "banana", "cherry"),
    pattern = c("p", "n", "h"),
    replacement = c("x", "f", "q"),
    stringsAsFactors = FALSE
)

# Define the function to extract the specific row index
# of the dataframe as a vector
get_row_vec <- function(df, row_idx){
    df %>% 
        dplyr::slice(row_idx) %>% 
        base::unlist() %>% 
        base::as.vector()
}

# Try and apply get_row_vec rowwise on the dataframe
# NOTE: This does not work! Need help to fix this
purrr::pmap(.l = df, ~get_row_vec(df  = .l, row_idx = 1))
#> Error in eval(lhs, parent, parent): object '.l' not found

请有人帮忙纠正上述代码并取悦 通过purrr帮助我了解如何执行此操作?

编辑:根据以下评论,这是我通过purrr寻求的理想输出

# MANUAL version of desired output
output <- list(get_row_vec(df, 1),
               get_row_vec(df, 2),
               get_row_vec(df, 3))
output
#> [[1]]
#> [1] "apple" "p"     "x"    
#> 
#> [[2]]
#> [1] "banana" "n"      "f"     
#> 
#> [[3]]
#> [1] "cherry" "h"      "q"

由于

3 个答案:

答案 0 :(得分:2)

您可以将purrr::transpose用于此目的:

library(purrr)
map(transpose(df), unlist, use.names = F)

#[[1]]
#[1] "apple" "p"     "x"    

#[[2]]
#[1] "banana" "n"      "f"     

#[[3]]
#[1] "cherry" "h"      "q"  

或者如果使用pmap

pmap(df, c, use.names = F)

#[[1]]
#[1] "apple" "p"     "x"    

#[[2]]
#[1] "banana" "n"      "f"     

#[[3]]
#[1] "cherry" "h"      "q"   

答案 1 :(得分:0)

这个怎么样?

map(t(df) %>% as.data.frame(), ~unname(unlist(.x)))
#$V1
#[1] apple p     x
#Levels: apple p x
#
#$V2
#[1] banana n      f
#Levels: banana f n
#
#$V3
#[1] cherry h      q
#Levels: cherry h q

避免factor s

map(t(df) %>% as.data.frame(), ~unname(as.character(unlist(.x))))
#$V1
#[1] "apple" "p"     "x"
#
#$V2
#[1] "banana" "n"      "f"
#
#$V3
#[1] "cherry" "h"      "q"

答案 2 :(得分:0)

最快的基地R:

as.list(data.frame(t(df),stringsAsFactors = F))
$X1
[1] "apple" "p"     "x"    

$X2
[1] "banana" "n"      "f"     

$X3
[1] "cherry" "h"      "q"   

或者你可以这样做:

 split(unname(unlist(df)),c(row(df)))#split(unlist(df,use.names = F),c(row(df)))
$`1`
[1] "apple" "p"     "x"    

$`2`
[1] "banana" "n"      "f"     

$`3`
[1] "cherry" "h"      "q"