我有一个数据框,希望将每一行提取到一个列表中
强制作为向量。我只想使用 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
有人可以帮忙纠正上面的代码吗?
帮助我了解如何使用 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"
谢谢
最佳答案
您可以使用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"
关于r - purrr - 将数据帧的行提取为向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50731645/