gpt4 book ai didi

r - 错误: incompatible size when mutating in dplyr

转载 作者:行者123 更新时间:2023-12-01 23:52:10 29 4
gpt4 key购买 nike

我在使用 dplyr 中的 mutate 函数时遇到问题,错误提示:

Error: incompatible size (0), expecting 5 (the group size) or 1

之前有一些帖子,我尝试了一些解决方案,但我的案例没有运气。

group-factorial-data-with-multiple-factors-error-incompatible-size-0-expe

r-dplyr-using-mutate-with-na-omit-causes-error-incompatible-size-d

grouped-operations-that-result-in-length-not-equal-to-1-or-length-of-group-in-dp

这是我尝试过的,

ff <- c(seq(0,0.2,0.1),seq(0,-0.2,-0.1))
flip <- c(c(0,0,1,1,1,1),c(1,1,0,0,0,0))
df <- data.frame(ff,flip,group=gl(2,6))

> df
ff flip group
1 0.0 0 1
2 0.1 0 1
3 0.2 1 1
4 0.0 1 1
5 -0.1 1 1
6 -0.2 1 1
7 0.0 1 2
8 0.1 1 2
9 0.2 0 2
10 0.0 0 2
11 -0.1 0 2
12 -0.2 0 2

我想根据以下条件添加名为 c1c2 的新组

 dff <- df%>%
group_by(group)%>%
mutate(flip=as.numeric(flip),direc=ifelse(c(0,diff(ff))<0,"backward","forward"))%>%
spread(direc,flip)%>%
arrange(group,group)%>%
mutate(c1=ff[head(which(forward>0),1)],c2=ff[tail(which(backward>0),1)])

Error: incompatible size (0), expecting 5 (the group size) or 1

我还添加了 do 并尝试过

do(data.frame(., c1=ff[head(which(.$forward>0),1)],c2=ff[tail(which(.$backward>0),1)]))

Error in data.frame(., c1 = ff[head(which(.$forward > 0), 1)], c2 = ff[tail(which(.$backward > : arguments imply differing number of rows: 5, 1, 0

但是当我只mutate c1列时,一切似乎都正常。为什么?

最佳答案

只是扩展@allistaire的评论。

  1. 您指定的条件是导致错误的原因。具体来说,tail(which(backward>0),1)
  2. 可以优化给定的代码以消除 spread()

你可以试试

dff <- df%>%
group_by(group)%>%
mutate(flip=as.numeric(flip),direc=ifelse(c(0,diff(ff))<0,"backward","forward"))%>%
arrange(group)%>%
mutate(c1=ff[head(which(direc=="forward" & flip > 0),1)])
<小时/>

您似乎正在寻找识别流入点,其中 direction更改,对于每个 group 。在这种情况下,请明确说明翻转是如何相关的,或者如果您更改 flip <- c(c(0,0,1,1,1,1),c(1,1,0,0,0,0))flip <- c(c(0,0,1,1,1,1),c(1,1,0,1,1,1))这样flip标记向 ff 方向变化,您可以使用

dff <- df%>%
group_by(group)%>%
mutate(flip=as.numeric(flip),direc=ifelse(c(0,diff(ff))<0,"backward","forward"))%>%
arrange(group)%>%
mutate(c1=ff[head(which(direc=="forward" & flip > 0),1)]) %>%
mutate(c2=ff[tail(which(direc=="backward"& flip >0),1)])

给出:

Source: local data frame [12 x 6]
Groups: group [2]

ff flip group direc c1 c2
<dbl> <dbl> <fctr> <chr> <dbl> <dbl>
1 0.0 0 1 forward 0.2 -0.2
2 0.1 0 1 forward 0.2 -0.2
3 0.2 1 1 forward 0.2 -0.2
4 0.0 1 1 backward 0.2 -0.2
5 -0.1 1 1 backward 0.2 -0.2
6 -0.2 1 1 backward 0.2 -0.2
7 0.0 1 2 forward 0.0 -0.2
8 0.1 1 2 forward 0.0 -0.2
9 0.2 0 2 forward 0.0 -0.2
10 0.0 1 2 backward 0.0 -0.2
11 -0.1 1 2 backward 0.0 -0.2
12 -0.2 1 2 backward 0.0 -0.2

关于r - 错误: incompatible size when mutating in dplyr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41671856/

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