在R中,“order”类似于Stata中的“sort”。这里有一个数据集的示例(仅列出变量名):
为了在Stata中获得相同的输出,我需要运行两行代码:
在理想的数据中,我们可以了解我们想要处理的变量的位置。但在大多数实际情况下,我们会有像“年龄”、“性别”这样没有位置指示器的变量,并且在一个数据集中可能有50个以上的变量。这时,Stata 中的“order”优势就更加明显了。我们不需要知道变量的确切位置,只需要输入它的名称即可。
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))
?rbind
。如果传递给rbind
的参数是数据框,则按名称匹配列而不是位置。无需对它们进行排序。 - Rolandretweetinfo <- retweetinfo[,c(1:5,7:12,17:18,13:15,6,16)]
是完全不必要的... - Ben Bolker