[英]dplyr::rowwise, mutate, and NA error
I'm trying to use rowwise
and mutate
with a function that can return an NA value, but am getting an error. 我正在尝试按行使用
rowwise
并使用可以返回NA值的函数进行mutate
,但出现错误。 Consider this contrived example (which obviously is not a case for rowwise, but illustrates the error): 考虑一下这个人为的例子(显然不是逐行的情况,而是说明了错误):
This works: 这有效:
library(dplyr)
data.frame(k=rnorm(10)) %>% mutate(l = ifelse(k > 0, 1, NA))
k l
1 -1.40223573 NA
2 1.47581873 1
3 0.35938746 1
4 0.87240448 1
5 -0.61991535 NA
6 -1.88152820 NA
7 0.25837350 1
8 -0.02250385 NA
9 0.92757943 1
10 0.49023792 1
But this gives an error: 但这给出了一个错误:
library(dplyr)
data.frame(k=rnorm(10)) %>% rowwise() %>% mutate(l = ifelse(k > 0, 1, NA))
Error: incompatible types, expecting a numeric vector
Note: I have filed github issue #1448 regarding the error in the result of this answer. 注意:我已经提交了关于此答案结果中的错误的github问题#1448 。
Update Oct 29, 2015: It looks like this bug in rowwise()
has been fixed. 2015年10月29日更新:似乎已修复了
rowwise()
此错误。 Check the link above for the details. 检查上面的链接以获取详细信息。
First off, there is no reason to make this a row-wise operation. 首先,没有理由进行逐行操作。
As far as the error goes, NA
is of logical type. 就错误而言,
NA
是逻辑类型。 You will need to use NA_real_
in your call to ifelse()
in this row-wise operation. 在此按行操作中,您需要在对
ifelse()
调用中使用NA_real_
。 Or as Ben Bolker notes in the comments below, you can wrap ifelse()
with as.numeric()
. 或者,如本·
ifelse()
Ben Bolker)在下面的注释中指出的那样,您可以将ifelse()
与as.numeric()
包装ifelse()
。
data.frame(k = rnorm(10)) %>%
rowwise() %>%
mutate(l = ifelse(k > 0, 1, NA_real_))
# Source: local data frame [10 x 2]
# Groups: <by row>
#
# k l
# (dbl) (dbl)
# 1 -1.7105691140 NA
# 2 -0.0702667985 NA
# 3 -0.5505724960 NA
# 4 -0.7444839870 NA
# 5 -0.0005646999 NA
# 6 -0.3702584194 NA
# 7 0.2596026787 1
# 8 0.4149810662 NA <-- error here pointed out by David A (see comments)
# 9 -0.4698540654 NA
# 10 1.0961705022 1
Note that you could also use integers, as in 请注意,您也可以使用整数,例如
mutate(l = ifelse(k > 0, 1L, NA_integer_))
But you can't mix logicals and reals/integers in row-wise ops it seems. 但是您似乎无法在行操作中混用逻辑和实数/整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.