具有多个类的 pivot_longer 导致错误(“无通用类型") [英] pivot_longer with multiple classes causes error ("No common type")
问题描述
我在多列(即两个字符列和一个数字列)上运行 pivot_longer
.我遇到了与类不匹配相关的错误.
I am running pivot_longer
on multiple columns (i.e. two character columns and one numeric). I am encountering an error related to the class mismatch.
我已经调查了任何强制"选项的文档,但在 pivot_longer
中没有看到任何参数来指定要使用的类 -- 或允许函数自动检测最通用的类.
I have investigated the documentation for any "force" options and did not see any arguments within pivot_longer
to specify the class to use -- or to allow the function auto-detect the most general class.
pivot_longer
中是否有任何参数可以避免此错误?或者您是否需要在运行 pivot_longer
之前将列转换为单个类?
Are there any parameters within pivot_longer
to avoid this error? Or do you need to convert the columns to a single class before running pivot_longer
?
library(dplyr)
library(tidyr)
library(ggplot2) # Just for `diamonds` dataset
small_diamonds <- diamonds %>%
# Select a few columns (two character, one numeric, specifically integers)
select(cut, color, price) %>%
# Create a row_id
mutate(row_num = row_number())
# This works with `gather`
small_diamonds %>%
gather(key, val, - row_num)
# This fails due to class error:
small_diamonds %>%
# Pivot data
pivot_longer( - row_num,
names_to = "key",
values_to = "val")
# Output
# Error: No common type for `cut` <ordered<4bd7e>> and `price` <integer>.
# Call `rlang::last_error()` to see a backtrace
# Convert columns to a single class (character) and then use `pivot_longer`.
# Runs successfully
small_diamonds %>%
mutate_all(as.character) %>%
# Pivot data
pivot_longer( - row_num,
names_to = "key",
values_to = "val")
推荐答案
在这种情况下我们可以指定values_ptype
(因为值列的类型不同)
We can specify the values_ptype
in this case (as the value columns differ in types)
library(ggplot2)
library(tidyr)
library(dplyr)
small_diamonds %>%
pivot_longer( - row_num,
names_to = "key",
values_to = "val", values_ptypes = list(val = 'character'))
# A tibble: 161,820 x 3
# row_num key val
# <int> <chr> <chr>
# 1 1 cut Ideal
# 2 1 color E
# 3 1 price 326
# 4 2 cut Premium
# 5 2 color E
# 6 2 price 326
# 7 3 cut Good
# 8 3 color E
# 9 3 price 327
#10 4 cut Premium
# … with 161,810 more rows
这篇关于具有多个类的 pivot_longer 导致错误(“无通用类型")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!