R:横向/横向排序 [英] R: Sort Across/Horizontally

查看:139
本文介绍了R:横向/横向排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的表:

I have a table that looks like this:

V1 V2 V3 V4
E
O  W  I
F  A  Z  C
S  D  K  L

我想跨/水平排序,以便看起来像这样:

I want sort across/horizontally so that it looks like this:

V1 V2 V3 V4
E
I  O  W
A  C  F  Z
D  K  L  S

我尝试使用sortorder,但是我只能使它垂直排序或重新排列整个列.是否可以对单个行进行水平排序?

I tried using sort and order, but I can only get it to sort vertically or reorder entire columns. Is it possible to sort horizontally for individual row?

谢谢.

注意:我看不到我的问题和按行排序数据"之间的相似之处.解决方法甚至都不一样.

Note: I don't see the similarities between my question and "Sort data by row". The solution is not even the same.

推荐答案

您可以尝试

df[] <- t(apply(df,1,function(x) c(sort(x[x!='']), x[x==''])))
df
#  V1 V2 V3 V4
#1  E         
#2  I  O  W   
#3  A  C  F  Z
#4  D  K  L  S

缺少NA而不是''

df[df==''] <- NA
df[] <- t(apply(df, 1, function(x) x[order(x)]))
df[is.na(df)] <- '' #if needed

数据

df <- structure(list(V1 = c("E", "O", "F", "S"), V2 = c("", "W", "A", 
"D"), V3 = c("", "I", "Z", "K"), V4 = c("", "", "C", "L")), .Names = c("V1", 
"V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -4L))

这篇关于R:横向/横向排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆