繁体   English   中英

如何对 R 中的这些类型的数据进行排序

[英]How to sort these types of the data in R

我有 30 列,我想对它们进行排序。 似乎需要多个软件包,但我很难做到。 这是一个数据示例:

 df<-read.table (text=" Id Name Class bc1 M1 G1 23 Smith A1 13 13 12 19 John Z1 12 14 12 33 Rose OG1 14 13 14 66 Javid MO1 12 14 13 66 Javid MO2 12 13 14 23 Smith A11 12 13 12 33 Rose OG2 14 14 13 19 John Z11 12 12 12 ", header=TRUE)

我想得到这些数据:

 Id Name Class1 bc1 M1 G1 Class2 bc1 M1 G1 23 Smith A1 13 13 12 A11 12 13 12 19 John Z1 12 14 12 Z11 12 12 12 33 Rose OG1 14 13 14 OG2 14 14 13 66 Javid MO1 12 14 13 MO2 12 13 14

逻辑是每个 Id 都有不同的值,我想为它们生成列。 谢谢您的帮助。

我们可以创建一个序列列,然后使用pivot_wider

library(tidyr)
library(dplyr)
library(data.table)
library(stringr)
df %>%
   mutate(nm1 = rowid(Id, Name)) %>%
   pivot_wider(names_from = nm1, values_from = Class:G1)%>%
   select(Id, Name, order(as.integer(str_remove(names(.)[-(1:2)], ".*_"))) + 2)

-输出

# A tibble: 4 x 10
#     Id Name  Class_1 bc1_1  M1_1  G1_1 Class_2 bc1_2  M1_2  G1_2
#  <int> <chr> <chr>   <int> <int> <int> <chr>   <int> <int> <int>
#1    23 Smith A1         13    13    12 A11        12    13    12
#2    19 John  Z1         12    14    12 Z11        12    12    12
#3    33 Rose  OG1        14    13    14 OG2        14    14    13
#4    66 Javid MO1        12    14    13 MO2        12    13    14

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM