簡體   English   中英

在R中重新排序CSV文件的數據

[英]Re-order data of CSV file in R

我有從CSV文件中讀取的以下數據集:

1   6.5
2   12
3   9
4   16.2
5   7.5
1   13
2   6
3   2.8
4   26
5   30

我想將第二組(從13到30開始)的數據移動到:

1   6.5   13
2   12    6
3   9     2.8
4   16.2  26
5   7.5   30

請注意,此數據將寫入CSV文件。

我怎樣才能做到這一點? 我不知道如何在R中做到這一點

readng(數據集之后read.csvbase Rfreaddata.tableread_csvrowr )中,由“COL1”分組后創建的列名的一列,然后spread的“COL2”與“科隆”

library(tidvyerse)
df1 %>%
   group_by(col1) %>%
   mutate(colN = str_c("newcol_", row_number())) %>% 
   spread(colN, col2)
# A tibble: 5 x 3
# Groups:   col1 [5]
#   col1 newcol_1 newcol_2
#  <int>    <dbl>    <dbl>
#1     1      6.5     13  
#2     2     12        6  
#3     3      9        2.8
#4     4     16.2     26  
#5     5      7.5     30  

數據

df1 <-structure(list(col1 = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L
  ), col2 = c(6.5, 12, 9, 16.2, 7.5, 13, 6, 2.8, 26, 30)),
  class = "data.frame", row.names = c(NA, 
 -10L))

一些“黑客”。 您可以重新name並刪除row.names

df2<-df[duplicated(df$V1),]
df1<-df[!duplicated(df$V1),]
res<-cbind(df2,df1)
res[,c(2,ncol(res))]

結果:

     V2 V2.1
6  13.0  6.5
7   6.0 12.0
8   2.8  9.0
9  26.0 16.2
10 30.0  7.5

數據:

df<-read.table(text="1   6.5
2   12
               3   9
               4   16.2
               5   7.5
               1   13
               2   6
               3   2.8
               4   26
               5   30",header=F)

您可以使用data.tablesplitstackshape在一行中實現此splitstackshape

> library(splitstackshape)
> library(data.table)
> cSplit(setDT(dt)[, list(text=paste(V2, collapse=',')), by = V1],"text")

   V1 text_1 text_2
1:  1    6.5   13.0
2:  2   12.0    6.0
3:  3    9.0    2.8
4:  4   16.2   26.0
5:  5    7.5   30.0

要么

另一個復雜的解決方案

> dcast(dt, V1~V2 ,value.var="V2")
> data.table::as.data.table(t(apply( df, 1, function(x) c(x[!is.na(x)], x[is.na(x)]))))[,.(V1,`1_6.5`,`1_13`)]

       V1 1_6.5 1_13
    1:  1   6.5   13
    2:  2   6.0   12
    3:  3   2.8    9
    4:  4  16.2   26
    5:  5   7.5   30

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM