有没有与Stata的'order'命令等效的R函数?

5
在R中,“order”类似于Stata中的“sort”。这里有一个数据集的示例(仅列出变量名):

v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18

以下是我期望的输出:

v1 v2 v3 v4 v5 v7 v8 v9 v10 v11 v12 v17 v18 v13 v14 v15 v6 v16

在R中,我有两种方法:
data <- data[,c(1:5,7:12,17:18,13:15,6,16)]

或者

names <- c("v1", "v2", "v3", "v4", "v5", "v7", "v8", "v9", "v10", "v11", "v12",  "v17", "v18", "v13", "v14", "v15", "v6", "v16")
data <- data[names]

为了在Stata中获得相同的输出,我需要运行两行代码:
order v17 v18, before(v13)
order v6 v16, last

在理想的数据中,我们可以了解我们想要处理的变量的位置。但在大多数实际情况下,我们会有像“年龄”、“性别”这样没有位置指示器的变量,并且在一个数据集中可能有50个以上的变量。这时,Stata 中的“order”优势就更加明显了。我们不需要知道变量的确切位置,只需要输入它的名称即可。
order age, after(gender)

在R中有基本的函数来处理这个问题吗,还是需要获取一个包?提前感谢。

tweetinfo <- data.frame(uid=1:50, mid=2:51, annotations=3:52, bmiddle_pic=4:53, created_at=5:54, favorited=6:55, geo=7:56, in_reply_to_screen_name=8:57, in_reply_to_status_id=9:58, in_reply_to_user_id=10:59, original_pic=11:60, reTweetId=12:61, reUserId=13:62, source=14:63, thumbnail_pic=15:64, truncated=16:65)
noretweetinfo <- data.frame(uid=21:50, mid=22:51, annotations=23:52, bmiddle_pic=24:53, created_at=25:54, favorited=26:55, geo=27:56, in_reply_to_screen_name=28:57, in_reply_to_status_id=29:58, in_reply_to_user_id=30:59, original_pic=31:60, reTweetId=32:61, reUserId=33:62, source=34:63, thumbnail_pic=35:64, truncated=36:65)
retweetinfo <- data.frame(uid=41:50, mid=42:51, annotations=43:52, bmiddle_pic=44:53, created_at=45:54, deleted=46:55, favorited=47:56, geo=48:57, in_reply_to_screen_name=49:58, in_reply_to_status_id=50:59, in_reply_to_user_id=51:60, original_pic=52:61, source=53:62, thumbnail_pic=54:63, truncated=55:64)
tweetinfo$type <- "ti"
noretweetinfo$type <- "nr"
retweetinfo$type <- "rt"
gtinfo <- rbind(tweetinfo, noretweetinfo)
gtinfo$deleted=""
gtinfo <- gtinfo[,c(1:16,18,17)]
retweetinfo <- transform(retweetinfo, reTweetId="", reUserId="")
retweetinfo <- retweetinfo[,c(1:5,7:12,17:18,13:15,6,16)]
gtinfo <- rbind(gtinfo, retweetinfo)
write.table(gtinfo, file="C:/gtinfo.txt", row.names=F, col.names=T, sep="\t", quote=F)
# rm(list=ls(all=T))

为什么您想要对列进行排序?通常情况下,人们并不关心数据框(data.frame)中列(变量)的顺序,而只关心行(观测值)的顺序。 - Roland
...甚至行的顺序通常是多余的,除非观察结果有明显的顺序,例如在时间序列中。 - Paul Hiemstra
5
请用可重现代码的形式提出问题。这样做可以更轻松地完成,并且效果会更好。 - Roland
2
请阅读?rbind。如果传递给rbind的参数是数据框,则按名称匹配列而不是位置。无需对它们进行排序。 - Roland
1
回复@Roland的评论:这意味着(我认为)命令retweetinfo <- retweetinfo[,c(1:5,7:12,17:18,13:15,6,16)]是完全不必要的... - Ben Bolker
显示剩余3条评论
6个回答

3

因为我在拖延并尝试不同的事情,所以我写了一个函数。最终,它取决于append

moveme <- function(invec, movecommand) {
  movecommand <- lapply(strsplit(strsplit(movecommand, ";")[[1]], ",|\\s+"), 
                        function(x) x[x != ""])
  movelist <- lapply(movecommand, function(x) {
    Where <- x[which(x %in% c("before", "after", "first", "last")):length(x)]
    ToMove <- setdiff(x, Where)
    list(ToMove, Where)
  })
  myVec <- invec
  for (i in seq_along(movelist)) {
    temp <- setdiff(myVec, movelist[[i]][[1]])
    A <- movelist[[i]][[2]][1]
    if (A %in% c("before", "after")) {
      ba <- movelist[[i]][[2]][2]
      if (A == "before") {
        after <- match(ba, temp)-1
      } else if (A == "after") {
        after <- match(ba, temp)
      }    
    } else if (A == "first") {
      after <- 0
    } else if (A == "last") {
      after <- length(myVec)
    }
    myVec <- append(temp, values = movelist[[i]][[1]], after = after)
  }
  myVec
}

以下是代表数据集名称的示例数据:

x <- paste0("v", 1:18)

现在假设我们想要先获取"v17"和"v18",然后才是"v3"、"v6"和"v16",最后是"v5":

moveme(x, "v17, v18 before v3; v6, v16 last; v5 first")
#  [1] "v5"  "v1"  "v2"  "v17" "v18" "v3"  "v4"  "v7"  "v8"  "v9"  "v10" "v11" "v12"
# [14] "v13" "v14" "v15" "v6"  "v16"

因此,显而易见的用法是针对一个名为“df”的data.frame
df[moveme(names(df), "how you want to move the columns")]

对于一个名为“DT”的data.table(正如@mnel指出的那样,这将更具内存效率):

setcolorder(DT, moveme(names(DT), "how you want to move the columns"))

请注意,复合移动由分号指定。

已识别的移动方式包括:

  • before(将指定的列移动到另一个命名列之前)
  • after(将指定的列移动到另一个命名列之后)
  • first(将指定的列移动到第一位置)
  • last(将指定的列移动到最后位置)

2
我明白你的问题。我现在有代码可以提供:
move <- function(data,variable,before) {
  m <- data[variable]
  r <- data[names(data)!=variable]
  i <- match(before,names(data))
  pre <- r[1:i-1]
  post <- r[i:length(names(r))]
  cbind(pre,m,post)
}

# Example.
library(MASS)
data(painters)
str(painters)

# Move 'Expression' variable before 'Drawing' variable.
new <- move(painters,"Expression","Drawing")
View(new)

这是一种非常创新的思维方式,将数据分成三部分。现在它可能无法解决多变量重定位的问题,但我们可以进一步发展这种方法。非常感谢。 - leoce
1
请注意,这种方法不高效,对于大型数据集或循环内部应避免使用。 - Roland
@Roland,仅仅按变量顺序的原则是低效的,但我发现它就像变量名一样,有时需要进行修复。 - Fr.
@leoce 如果你需要的话,可以将函数的variable参数设置为变量向量:将r变量更改为data [!(names(data)%in%variable)] - Fr.
@Fr. 不,我的意思是你的函数不够高效。特别是,分割数据框和cbinding是低效的操作,在这里可以避免使用。 - Roland

2
您可以编写自己的函数来完成这个任务。
下面的语句将使用类似于 stata 的语法为您的列名提供新的顺序:
- `where` 是一个命名列表,有 4 种可能性: - `list(last = T)` - `list(first = T)` - `list(before = x)` 其中 `x` 是要查询的变量名 - `list(after = x)` 其中 `x` 是要查询的变量名
- `sorted = T` 将按字典顺序(一种“字母顺序”和“序数”组合的方式)对 `var_list` 进行排序。
此函数仅对名称进行操作(一旦将 `data.frame` 对象作为 `data` 传递后),并返回重新排列的名称列表。
例如:
stata.order <- function(var_list, where, sorted = F, data) {
    all_names = names(data)
    # are all the variable names in
    check <- var_list %in% all_names
    if (any(!check)) {
        stop("Not all variables in var_list exist within  data")
    }
    if (names(where) == "before") {
        if (!(where %in% all_names)) {
            stop("before variable not in the data set")
        }
    }
    if (names(where) == "after") {
        if (!(where %in% all_names)) {
            stop("after variable not in the data set")
        }
    }

    if (sorted) {
        var_list <- sort(var_list)
    }
    where_in <- which(all_names %in% var_list)
    full_list <- seq_along(data)
    others <- full_list[-c(where_in)]

    .nwhere <- names(where)
    if (!(.nwhere %in% c("last", "first", "before", "after"))) {
        stop("where must be a list of a named element first, last, before or after")
    }

    do_what <- switch(names(where), last = length(others), first = 0, before = which(all_names[others] == 
        where) - 1, after = which(all_names[others] == where))

    new_order <- append(others, where_in, do_what)
    return(all_names[new_order])
}

tmp <- as.data.frame(matrix(1:100, ncol = 10))

stata.order(var_list = c("V2", "V5"), where = list(last = T), data = tmp)

##  [1] "V1"  "V3"  "V4"  "V6"  "V7"  "V8"  "V9"  "V10" "V2"  "V5" 

stata.order(var_list = c("V2", "V5"), where = list(first = T), data = tmp)

##  [1] "V2"  "V5"  "V1"  "V3"  "V4"  "V6"  "V7"  "V8"  "V9"  "V10"

stata.order(var_list = c("V2", "V5"), where = list(before = "V6"), data = tmp)

##  [1] "V1"  "V3"  "V4"  "V2"  "V5"  "V6"  "V7"  "V8"  "V9"  "V10"

stata.order(var_list = c("V2", "V5"), where = list(after = "V4"), data = tmp)

##  [1] "V1"  "V3"  "V4"  "V2"  "V5"  "V6"  "V7"  "V8"  "V9"  "V10"

# throws an error
stata.order(var_list = c("V2", "V5"), where = list(before = "v11"), data = tmp)

## Error: before variable not in the data set

如果您想进行内存高效的重新排序(通过引用,而不是复制),请使用data.table

DT <- data.table(tmp)
# sets by reference, no copying
setcolorder(DT, stata.order(var_list = c("V2", "V5"), where = list(after = "V4"), 
    data = DT))

DT

##     V1 V3 V4 V2 V5 V6 V7 V8 V9 V10
##  1:  1 21 31 11 41 51 61 71 81  91
##  2:  2 22 32 12 42 52 62 72 82  92
##  3:  3 23 33 13 43 53 63 73 83  93
##  4:  4 24 34 14 44 54 64 74 84  94
##  5:  5 25 35 15 45 55 65 75 85  95
##  6:  6 26 36 16 46 56 66 76 86  96
##  7:  7 27 37 17 47 57 67 77 87  97
##  8:  8 28 38 18 48 58 68 78 88  98
##  9:  9 29 39 19 49 59 69 79 89  99
## 10: 10 30 40 20 50 60 70 80 90 100

1

dplyr和函数dplyr::relocate是在dplyr 1.0.0中引入的一个新动词,它可以完美地实现您所需的功能。

library(dplyr)

data %>% relocate(v17, v18, .before = v13)

data %>% relocate(v6, v16, .after = last_col())

data %>% relocate(age, .after = gender)


0

这应该会给你相同的文件:

#snip
gtinfo <- rbind(tweetinfo, noretweetinfo)
gtinfo$deleted=""
retweetinfo <- transform(retweetinfo, reTweetId="", reUserId="")
gtinfo <- rbind(gtinfo, retweetinfo)
gtinfo <-gtinfo[,c(1:16,18,17)]
#snip

在R中实现类似Strata的order函数是可能的,但我认为需求不是很大。


嗯,这对于所有人来说并不是一个大问题,有兴趣的人可以去了解一下。 - leoce
@leoce 我的观点是,你只对此感兴趣,是因为你还是R的新手并且是从Stata转来的。我在我的回答中说明了,你不需要用排序来使你的代码凌乱。事实上,你只需要进行一次排序,那也只是因为你想要在输出文件中得到特定的顺序。 - Roland
你说得对,gtinfo <-gtinfo[,c(1:16,18,17)] 最后比我用两行代码 c(1:5,7:12,17:18,13:15,6,16) 好。但你不能否认在 R 中没有这样的基本函数来调整列顺序。我不能 rbind 它并告诉我的老板“看,软件会自动排序,你最好习惯它”。 - leoce
我不明白。您可以使用上面显示的基本功能进行排序。如果您不想使用索引,也可以使用列名,可能需要使用 subset - Roland
数据 <- 数据[,c("A", "C", "B")] 或者 数据 <- 数据[,c(1,3,2)] 或者 数据 <- subset(数据, select=c(1,3,2)),这些都可以正常工作。但是如果我有50个或更多列,我必须手动键入所有列名或查找对象和目标的列号。 - leoce
显示剩余2条评论

0

你的意图非常不清楚,但是根据你的第一句话,我猜你想对数据集进行排序。

实际上,有一个内置的order函数,它会返回排序后的序列的索引。你是在找这个吗?

> x <- c(3,2,1)

> order(x)
[1] 3 2 1

> x[order(x)]
[1] 1 2 3

这是我最不想做的事情——整理数据。在Stata中,“Order”意味着另一件事,使用过它的人可以理解。 - leoce

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接