代码之家  ›  专栏  ›  技术社区  ›  user4687531

purr-将数据帧的行提取为向量

  •  1
  • user4687531  · 技术社区  · 6 年前

    我有一个数据框,希望将每一行提取到一个列表中 作为向量强制的。我只想用 tidyverse purrr 实现此目的的包。

    我有以下的 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
    

    有人能帮我纠正一下上面的代码吗 帮我弄明白怎么做 珀尔 ?

    编辑:根据下面的评论,这是我寻求的理想输出 珀尔

    # 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 回复  |  直到 6 年前
        1
  •  2
  •   akuiper    6 年前

    你可以使用 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"   
    
        2
  •  0
  •   Maurits Evers    6 年前

    这个怎么样?

    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"
    
        3
  •  0
  •   Onyambu    6 年前

    最快的基础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"