在数据框中排序行(Order rows in data frame)

编程入门 行业动态 更新时间:2024-10-23 14:29:21
在数据框中排序行(Order rows in data frame)

我知道这可能是一个特殊的问题,但是:

我有一个看起来或多或少像这样的数据框:

t1 t2 t3 t4 o1 NA 1 1 1 o2 1 NA NA NA o3 NA NA 1 1 o4 1 1 NA NA o5 1 1 1 1

我想重新排序它所以它看起来像这样:

t1 t2 t3 t4 o3 NA NA 1 1 o1 NA 1 1 1 o5 1 1 1 1 o4 1 1 NA NA o2 1 NA NA NA

因此,如果我们从左下角向右上角走,那就是这个“隧道”(路径,无论如何)。 底行包含来自右侧的大多数NA,中间行没有,顶行是左侧具有NA的行(顶部具有最多的NA)。

是否有任何简单(或至少不太难)的方法来做到这一点? 数据帧也相对较大(400x3300)。 必须保持列名和行名。 然后我想采用这个数据框并制作热图。

I know this might be a peculiar question, but:

I have a data frame which looks more or less like this:

t1 t2 t3 t4 o1 NA 1 1 1 o2 1 NA NA NA o3 NA NA 1 1 o4 1 1 NA NA o5 1 1 1 1

I want to reorder it so it looks like this:

t1 t2 t3 t4 o3 NA NA 1 1 o1 NA 1 1 1 o5 1 1 1 1 o4 1 1 NA NA o2 1 NA NA NA

So as you can se if we go from the bottom left corner towards the upper right corner there's this "tunnel" (path, whatever). The bottom row contains the most NAs from the right, the middle rows have none and the top rows are the ones with NAs on the left (the top one having the most NAs).

Is there any easy (or at least not too hard) way to do this? Also the data frame is relatively big (400x3300). Column and row names must be perserved. I want to then take this data frame and make a heat map.

最满意答案

假设只有中间没有NA的行:

DF <- read.table(text=" t1 t2 t3 t4 o1 NA 1 1 1 o2 1 NA NA NA o3 NA NA 1 1 o4 1 1 NA NA o5 1 1 1 1", header=TRUE) DF1 <- DF[is.na(DF$t1),] DF2 <- DF[rowSums(is.na(DF))==0,] DF3 <- DF[is.na(DF$t4),] DF1 <- DF1[order(-rowSums(is.na(DF1))),] DF3 <- DF3[order(rowSums(is.na(DF3))),] DF <- rbind(DF1,DF2,DF3) # t1 t2 t3 t4 # o3 NA NA 1 1 # o1 NA 1 1 1 # o5 1 1 1 1 # o4 1 1 NA NA # o2 1 NA NA NA

Assuming there are no rows with NAs only in the middle:

DF <- read.table(text=" t1 t2 t3 t4 o1 NA 1 1 1 o2 1 NA NA NA o3 NA NA 1 1 o4 1 1 NA NA o5 1 1 1 1", header=TRUE) DF1 <- DF[is.na(DF$t1),] DF2 <- DF[rowSums(is.na(DF))==0,] DF3 <- DF[is.na(DF$t4),] DF1 <- DF1[order(-rowSums(is.na(DF1))),] DF3 <- DF3[order(rowSums(is.na(DF3))),] DF <- rbind(DF1,DF2,DF3) # t1 t2 t3 t4 # o3 NA NA 1 1 # o1 NA 1 1 1 # o5 1 1 1 1 # o4 1 1 NA NA # o2 1 NA NA NA

更多推荐

本文发布于:2023-08-05 19:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1435780.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框中   数据   Order   frame   data

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!