我正在尝试将我最喜欢的R命令转移到tidyverse。在导入数据后,我通常首先检查每个变量的格式,例如:
data(cars)
sapply(cars, class)
# speed dist
# "numeric" "numeric"变成:
library(tidyverse)
exam.table %>%
sapply(class)
# speed dist
# "numeric" "numeric"那么你如何在tidyverse中转置它呢?旧版本是:
t(t(sapply(cars,class)))
# [,1]
# speed "numeric"
# dist "numeric"发布于 2021-04-21 21:53:44
cars %>% sapply(class) %>% as.data.frame() %>% rownames_to_column("col")
col .
1 speed numeric
2 dist numeric或
cars %>% sapply(class) %>% as.data.frame()
.
speed numeric
dist numeric发布于 2021-04-21 21:42:13
一个非常“杂乱无章”的散文可能是:
cars %>% map_df(class) %>% t()
[,1]
speed "numeric"
dist "numeric"发布于 2021-04-21 21:58:30
sapply的“整洁”等价物是purrr::map family of functions。在您的情况下,map_chr
map_chr(df, class)如果想要data.frame格式的结果,只需将其包装在tibble中即可
tibble(cols = names(cars), class = map_chr(cars, class))…当然,你也可以通过管道表示法来实现这一点:
cars %>% {tibble(col = names(.), class = map_chr(., class))}或
cars %>% map_chr(class) %>% tibble(col = names(.), class = .)https://stackoverflow.com/questions/67196980
复制相似问题