Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.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
在dataframe中,按一列排列一些观察值,按另一列排列其他观察值_R_Dplyr - Fatal编程技术网

在dataframe中,按一列排列一些观察值,按另一列排列其他观察值

在dataframe中,按一列排列一些观察值,按另一列排列其他观察值,r,dplyr,R,Dplyr,我有以下数据帧: dat<- data.frame(question=c("Question 1", "Question 3", "Question 2", "Question 2", "Question 3", "Question 1"), answer=c("Answer 1",

我有以下数据帧:

dat<- data.frame(question=c("Question 1", "Question 3", "Question 2", 
                      "Question 2", "Question 3", "Question 1"),
           answer=c("Answer 1", "Answer 1", "1- Yes", "No",
                    "Answer 2", "Answer 2"),
           total=c(40,70,20,80,30,60))
dat

#    question   answer total
# 1 Question 1 Answer 1    40
# 2 Question 3 Answer 1    70
# 3 Question 2   1- Yes    20
# 4 Question 2       No    80
# 5 Question 3 Answer 2    30
# 6 Question 1 Answer 2    60
我怎样才能做到这一点?理想情况下,我想要一个使用Dplyr的
arrange()
的解决方案。我尝试过将
arrange()
ifelse()
组合起来,但没有得到我想要的结果。这就是我尝试过的:

library(tidyverse)
dat %>% arrange(question, ifelse(question=="Question 2", answer, desc(total)))

与case_一起安排应在何时开展工作:


dat%>%排列(
问题:,
什么时候(
问题%c(“问题1”、“问题3”)中的%为双倍(说明(总数)),
问题==“问题2”~as.double(xtfrm(答案))
)
)
现在我有点困惑为什么那里需要as.double,但它却抱怨其他,并且似乎在那里做了正确的事情

顺便说一句,您的方法与
as.double一起工作:


dat%>%排列(问题,如果有其他(问题==“问题2”,作为.double(xtfrm(答案)),作为.double(描述(总数)))

(但仅限于处理两列,除非嵌套多个if_else(dplyr::if_else优于base::ifelse))

您可以使用
arrange()的
.by_group
参数

library(tidyverse)
dat %>% arrange(question, ifelse(question=="Question 2", answer, desc(total)))
    dat %>% 
        group_by(question) %>% 
        arrange(.by_group = T, desc(ifelse(question == "Question 2", answer, total)) )
        %>% ungroup()