我正在对多列运行pivot_longer
(即两个字符列和一个数字列)。我遇到了与类不匹配相关的错误。
我查看了文档,没有发现任何“强制”选项,在pivot_longer
中指定要使用的类别,或允许函数自动检测最通用的类别的参数。
有没有pivot_longer
内部的参数可以避免此错误?还是需要在运行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")
val
,但是你的值列实际上被命名为b
,当我将val
替换为b
时,转换在我的机器上可以正常工作。 - Koray