我有一个值数据集,其中有多个列(针对不同的站点)和行(针对不同的日子),我试图使用R对每一天进行排序。我希望将每一列(站点)的数据从一天内的站点总数中排序(因此根据每一行进行排序)。在Excel中可以这样做,但显然需要很长时间。下面是一个小得多的例子,说明我正在努力实现的目标:
date - site1 - site2 - site3 - site4
1/1/00 - 24 - 33 - 10 - 13
2/1/00 - 13 - 25 - 6 - 2
~~ leading to:
date - site1 - site2 - site3 - site4
1/1/00 - 2 - 1 - 4 - 3
2/1/00 - 2 - 1 - 3 - 4希望有一些简单的命令,非常感谢!
发布于 2014-05-08 00:39:34
您可以使用rank给出数据的级别。
# your data
mydf <- read.table(text="date - site1 - site2 - site3 - site4
1/1/00 - 24 - 33 - 10 - 13
2/1/00 - 13 - 25 - 6 - 2", sep="-", header=TRUE)
# find ranks
t(apply(-mydf[-1], 1, rank))
# add to your dates
mydf.rank <- cbind(mydf[1], t(apply(-mydf[-1], 1, rank)))关于代码
mydf[-1] # removes the first column
-mydf[-1] #using the `-` negates the values -so the rank goes in decreasing orderapply与MARGIN=1一起查找跨行的级别
t转换矩阵以提供您想要的输出
发布于 2018-03-07 03:35:00
这是一种整洁的方式。
重组为长格式、排序(排列)、组和扩展。唯一棘手的部分是知道排序组意味着您已经自动对它们进行了排序(升序或降序)。函数row_number承认这一点。
library(tidyverse)
library(lubridate)
# Data
df <- tribble(
~date, ~site1, ~site2, ~site3, ~site4,
mdy("1/1/2000"), 24, 33, 10, 13,
mdy("2/1/2000"), 13, 25, 6, 2
)
df %>%
gather(site, days, -date) %>% #< Make Tidy
arrange(date, desc(days)) %>% #< Sort relevant columns
group_by(date) %>%
mutate(ranking = row_number()) %>% #< Ranking function
select(-days) %>% #< Remove unneeded column. Worth keeping in tidy format!
spread(site, ranking)
#> # A tibble: 2 x 5
#> # Groups: date [2]
#> date site1 site2 site3 site4
#> <date> <int> <int> <int> <int>
#> 1 2000-01-01 2 1 4 3
#> 2 2000-02-01 2 1 3 4
Created on 2018-03-06 by the reprex package (v0.2.0).https://stackoverflow.com/questions/23530731
复制相似问题