对多个数据帧进行排序并在R中求和
我有10个数据帧,每个数据帧有2列,我称之为数据帧a、b、c、d、e、f、g、h、I和j 对于序列,每个数据帧中的第一列称为s,对于对应于每个序列的p值,第二列称为p。s列在所有10个数据帧中包含相同的序列,本质上唯一的区别在于p值。 下面是数据帧a的简短版本,它有600000行对多个数据帧进行排序并在R中求和,r,sum,ranking,data-manipulation,R,Sum,Ranking,Data Manipulation,我有10个数据帧,每个数据帧有2列,我称之为数据帧a、b、c、d、e、f、g、h、I和j 对于序列,每个数据帧中的第一列称为s,对于对应于每个序列的p值,第二列称为p。s列在所有10个数据帧中包含相同的序列,本质上唯一的区别在于p值。 下面是数据帧a的简短版本,它有600000行 s p gtcg 0.06 gtcgg 0.05 gggaa 0.07 cttg 0.05 我想用p值对每个数据帧进行排名,最小的p值应该得到1的排名,相等的p值应该得到相同的排名。每
s p
gtcg 0.06
gtcgg 0.05
gggaa 0.07
cttg 0.05
我想用p值对每个数据帧进行排名,最小的p值应该得到1的排名,相等的p值应该得到相同的排名。每个最终数据帧应采用以下格式:
s p_rank_a
gtcg 2
gtcgg 1
gggaa 3
cttg 1
我用这个做了一个:
r我会将所有
数据.frames
放在列表中
,然后使用lappy
和转换
,如下所示:
my_l <- list(a,b,c) # all your data.frames
# you can use rank but it'll give you the average in case of ties
# lapply(my_l, function(x) transform(x, rank_p = rank(p)))
# I prefer this method instead
my_o <- lapply(my_l, function(x) transform(x, p = as.numeric(factor(p))))
# now bind them in to a single data.frame
my_o <- do.call(rbind, my_o)
# now paste them
aggregate(data = my_o, p ~ s, function(x) paste(x, collapse=","))
# s p
# 1 cttg 1,1,1
# 2 gggaa 3,3,3
# 3 gtcg 2,2,2
# 4 gtcgg 1,1,1
试一试:对于单个data.frame,您可以只做一行,如下所示:
@Arun指出将
用作.numeric(因子(p))
库(data.table)
aDT的gggaa
的排名不应该是4而不是3吗?我不确定顺序(排名(p))
是否是这里需要的。例如:如果p=c(0.06,0.05,0.07,0.05)
,那么rank(p)=c(3,1.5,4,1.5)
和顺序(.)=2,4,1,3
,而期望的结果是2,1,3,1
。而顺序(p)
与顺序(秩(p))
@Arun是完全正确的。在我的脑海里,我在想楼层(排名(p))
,但即使这样也不完全正确。我已经编辑了我的答案。再次感谢你。我将把这个和你回答的另一个结合起来。这些数据帧的长度从600000行到240万行,你知道我可以用一个更快的程序吗。我对python略知一二,但仅此而已
my_l <- list(a,b,c) # all your data.frames
# you can use rank but it'll give you the average in case of ties
# lapply(my_l, function(x) transform(x, rank_p = rank(p)))
# I prefer this method instead
my_o <- lapply(my_l, function(x) transform(x, p = as.numeric(factor(p))))
# now bind them in to a single data.frame
my_o <- do.call(rbind, my_o)
# now paste them
aggregate(data = my_o, p ~ s, function(x) paste(x, collapse=","))
# s p
# 1 cttg 1,1,1
# 2 gggaa 3,3,3
# 3 gtcg 2,2,2
# 4 gtcgg 1,1,1
require(data.table)
# bind all your data.frames together
dt <- rbindlist(my_l) # my_l is your list of data.frames
# replace p-value with their "rank"
dt[, p := as.numeric(factor(p))]
# set key
setkey(dt, "s")
# combine them using `,`
dt[, list(p_ranks = paste(p, collapse=",")), by=s]
library(data.table)
aDT <- data.table(a)[, p_rank := as.numeric(factor(p))]
# collect them all
allOfThem <- lapply(letters[1:10], get, envir=.GlobalEnv)
# keep in mind you named an object `c`
# convert to DT and create the ranks
allOfThem <- lapply(allOfThem, function(x) data.table(x)[, p_rank := as.numeric(factor(p))])