【R语言陷阱】在tidyverse管道符中使用,一般(base)只输入一个向量的函数,报错

在这里插入图片描述

> cor_df %>% unique(.$x)
Error: 'incomparables != FALSE' 参数现在还没有用
> cor_df %>% table(.$x)
Error in xtfrm.data.frame(x) : 
  (converted from warning) cannot xtfrm data frames
> cor_df %>% duplicated(.$x)
Error: 'incomparables != FALSE' 参数现在还没有用
> cor_df %>% sum(.$value)
Error in FUN(X[[i]], ...) : 
  only defined on a data frame with all numeric-alike variables

查阅资料:

在r中使用unique()函数中的管道不起作用

R - unique() gives ‘incomparables != FALSE’ error
在这里插入图片描述
在这里插入图片描述
查看unique()函数帮助文档

unique(x, incomparables = FALSE, ...)

Arguments
x
a vector or a data frame or an array or NULL.

incomparables
a vector of values that cannot be compared. FALSE is a special value, meaning that all values can be compared, and may be the only value accepted for methods other than the default. It will be coerced internally to the same type as x.

看来是参数传递位置的问题
手动指定就好了

> cor_df %>% unique(x = .$x)
[1] "A" "B" "C"

但有的函数手动指定也不行

> cor_df %>% sum(.$value)
Error in FUN(X[[i]], ...) : 
  only defined on a data frame with all numeric-alike variables
> cor_df %>% sum(... =  .$value)
Error in FUN(X[[i]], ...) : 
  only defined on a data frame with all numeric-alike variables

在这里插入图片描述

> sum(c(1,2,3))
[1] 6
> sum(... =  c(1,2,3))
[1] 6

其他解决办法:
在这里插入图片描述

> cor_df %>% {unique(.$x)}
[1] "A" "B" "C"
> cor_df %>% {table(.$x)}

A B C 
3 2 1 
> cor_df %>% {duplicated(.$x)}
[1] FALSE  TRUE  TRUE FALSE  TRUE FALSE
> cor_df %>% {sum(.$value)}
[1] 13.99618

为什么加上大括号{}就行了目前还不清楚

What does |> (pipe greater than) mean in R?

在这里插入图片描述

Magrittr uses the . placeholder for the LHS and {} to place it arbitrarily.

感觉是为和其他非tidyverse框架下函数compatible设计的

tidyverse框架下函数目前还没见需要大括号

> cor_df %>% distinct()
  x y    value
1 A A 1.969946
2 A B 1.585933
3 A C 3.187764
4 B B 1.028659
5 B C 4.231538
6 C C 1.992336
> cor_df %>% distinct(.$x)
  .$x
1   A
2   B
3   C

在这里插入图片描述

> cor_df %>% distinct(.$x)
  .$x
1   A
2   B
3   C
> cor_df %>% {distinct(.$x)}
Error in UseMethod("distinct") : 
  no applicable method for 'distinct' applied to an object of class "character"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值