Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R仅当列具有特定值时排列_R - Fatal编程技术网

R仅当列具有特定值时排列

R仅当列具有特定值时排列,r,R,如何仅在列具有特定值时排列列/df。考虑下面的例子: df <- data.frame(a = c(1,1,1,2,2,2,3,3), b = c(1,2,3,4,5,6,7,8), c = c(0, 0.4, 0.3, 0, 0.2, -0.3, 0, -0.2)) # I only want to arrange the df (e.g. ascending) if c != 0: a b c 1 1

如何仅在列具有特定值时排列列/df。考虑下面的例子:

df <- data.frame(a = c(1,1,1,2,2,2,3,3),
                 b = c(1,2,3,4,5,6,7,8),
                 c = c(0, 0.4, 0.3, 0, 0.2, -0.3, 0, -0.2))


# I only want to arrange the df (e.g. ascending) if c != 0:

  a b    c
1 1 1  0.0
2 1 2  0.3
3 1 3  0.4
4 2 4  0.0
5 2 5 -0.2
6 2 6  0.3
7 3 7  0
8 3 8 -0.2




df我是否正确理解了您的问题您只需要数据帧,但如果c不是0,则只需要包含行

df <- df[df$c!=0,]

df使用
dplyr
可以执行以下操作:

library(dplyr)

df %>%
  group_by(grp = cumsum(c == 0)) %>%
  arrange(c != 0, c, .by_group = TRUE) %>%
  ungroup() %>%
  select(-grp)

#      a     b     c
#  <dbl> <dbl> <dbl>
#1     1     1   0  
#2     1     3   0.3
#3     1     2   0.4
#4     2     4   0  
#5     2     6  -0.3
#6     2     5   0.2
库(dplyr)
df%>%
分组依据(grp=cumsum(c==0))%>%
排列(c!=0,c,.by_group=TRUE)%>%
解组()%>%
选择(-grp)
#a、b、c
#    
#1     1     1   0  
#2     1     3   0.3
#3     1     2   0.4
#4     2     4   0  
#5     2     6  -0.3
#6     2     5   0.2

提供有关如何排列数据的更多信息?我认为最后两个值应该是-0.3和0.2.ohh,抱歉。我忘了升序了!处理玩具数据。我的数据是相似的,除了c的长度不同于a。因此dplyr抛出了一个错误:
order(c!=0,c,.by_group=TRUE)
参数的长度与
arrange不同(!c%in%0,c,.by_group=TRUE)
似乎不起作用,我将上述示例应用于不同长度的扩展情况,我仍然可以使用我的答案获得您帖子中显示的预期输出。(除了你仍然有-0.3和0.2互换)。是的,一些包冲突导致了故障,谢谢!