gpt4 book ai didi

r - 具有多个类的 hub_longer 会导致错误 ("No common type")

转载 作者:行者123 更新时间:2023-12-02 01:55:36 25 4
gpt4 key购买 nike

我正在多列(即两个字符列和一个数字列)上运行 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")

最佳答案

当使用 values_ptypes 参数时,错误现在以不同的形式再次出现。

library(tidyverse)

small_diamonds <- diamonds %>%
select(cut, color, price) %>%
mutate(row_num = row_number())

small_diamonds %>%
pivot_longer( - row_num,
names_to = "key",
values_to = "val",
values_ptypes = list(val = 'character'))
#> Error: Can't convert <integer> to <character>.

因此我需要使用 values_transform 参数来获得所需的结果。

library(tidyverse)

small_diamonds <- diamonds %>%
select(cut, color, price) %>%
mutate(row_num = row_number())

small_diamonds %>%
pivot_longer( - row_num,
names_to = "key",
values_to = "val",
values_transform = list(val = as.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

reprex package于2020年8月25日创建(v0.3.0)

关于r - 具有多个类的 hub_longer 会导致错误 ("No common type"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58124530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com