R在变量中按特定值排列行

问题描述 投票:0回答:2

我想在小标题中排列行,以使其中包含“ Gas”的值移到小标题的底部。

这是我的数据:

library(dplyr)

df1 <- tibble(
  col1 = c("ZBottom Gas","Almost Bottom Gas","Top","Bottom Gas", "Top"),
  col2 = c(5, 7, 4, 8,6))

这就是我希望数据看起来像的样子:

df1 <- tibble(
  col1 = c("Top", "Top", "ZBottom Gas","Almost Bottom Gas","Bottom Gas"),
  col2 = c(4, 6, 5, 7, 8))

[我知道我可以为Gas赋值为'2'的任何东西分配一个新变量,然后将其他所有值赋给'1'的东西,然后像这样使用sortlike:

df2 <- tibble(
  col1 = c("ZBottom Gas","Almost Bottom Gas","Top","Bottom Gas", "Top"),
  col2 = c(5, 7, 4, 8,6),
  arrange = c(2,2,1,2,1))

df2 %>% 
  arrange(arrange) -> df3

这很好,但我只是想知道是否有更简单的方法来做到这一点?

谢谢

r dplyr
2个回答
1
投票

我们可以使用str_detect检测"Gas"的存在并将其用于arrange

library(dplyr)
library(stringr)

df1 %>% arrange(str_detect(col1, 'Gas'))

#  col1               col2
#  <chr>             <dbl>
#1 Top                   4
#2 Top                   6
#3 ZBottom Gas           5
#4 Almost Bottom Gas     7
#5 Bottom Gas            8

在基本R中,可以使用ordergrepl完成。

df1[order(grepl('Gas', df1$col1)), ]

0
投票

[regexpr()也吃点小菜。

df1[order(regexpr("Gas", df1$col1)), ]
# # A tibble: 5 x 2
#   col1               col2
#   <chr>             <dbl>
# 1 Top                   4
# 2 Top                   6
# 3 Bottom Gas            8
# 4 ZBottom Gas           5
# 5 Almost Bottom Gas     7
© www.soinside.com 2019 - 2024. All rights reserved.