[英]purrr - extract rows of dataframe as vectors
I have a dataframe and wish to extract each row into a list coerced as a vector. 我有一个数据框,并希望将每一行提取到强制作为矢量的列表中。 I want to use only tidyverse
and purrr
packages to achieve this. 我只想使用tidyverse
和purrr
软件包来实现此目的。
I have the following reprex
where I tried to do this: 我在尝试执行此reprex
位置上具有以下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
Could anyone please help rectify the above code and please help me understand how to do this with purrr
? 任何人都可以帮助纠正以上代码,并请帮助我了解如何使用purrr
进行此purrr
吗?
EDIT: Per comments below, this is the ideal output I seek via 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"
Thanks 谢谢
You can use purrr::transpose
for this purpose: 您可以使用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"
Or if using pmap
: 或者如果使用pmap
:
pmap(df, c, use.names = F)
#[[1]]
#[1] "apple" "p" "x"
#[[2]]
#[1] "banana" "n" "f"
#[[3]]
#[1] "cherry" "h" "q"
How about this? 这个怎么样?
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
To avoid factor
s 避免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"
fastest Base R: 最快的Base R:
as.list(data.frame(t(df),stringsAsFactors = F))
$X1
[1] "apple" "p" "x"
$X2
[1] "banana" "n" "f"
$X3
[1] "cherry" "h" "q"
or you can do: 或者您可以执行以下操作:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.