问题

我在多列上运行pivot_longer(即两个字符列和一个数字).我遇到与类不匹配有关的错误.

我已经调查了任何“force”选项的文档,并且没有在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_ptype(因为值列在类型上有所不同)

 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
 

  相同标签的其他问题

rtidyr