簡體   English   中英

R:折疊行,然后將行轉換為新列

[英]R: collapse rows and then convert row into a new column

所以這是我的挑戰。 我試圖擺脫最好組織為一列的數據行。 原始數據集看起來像

1|1|a
2|3|b
2|5|c
1|4|d
1|2|e
10|10|f

最終的結果是

1 |1,2,4 |a| e d
2 |3,5   |b| c
10|10    |f| NA

表的整形基於第1列分組中的最小值Col 2,其中從該組中的最小值定義新列3,而從第4列的最小值開始折疊新列4。 嘗試的一些方法包括:

newTable[min(newTable[,(1%o%2)]),] ## returns the minimum of both COL 1 and 2 only

ddply(newTable,"V1", summarize, newCol = paste(V7,collapse = " ")) ## collapses all values by Col 1 and creates a new column nicely.

據我所知,部分將這些代碼行合並為一行的變體沒有用。 這些修改不包括在這里。

嘗試:

 library(dplyr)
 library(tidyr)

 dat %>% 
     group_by(V1) %>% 
     summarise_each(funs(paste(sort(.), collapse=","))) %>%
     extract(V3, c("V3", "V4"), "(.),?(.*)")

給出輸出

  #  V1    V2 V3  V4
  #1  1 1,2,4  a d,e
  #2  2   3,5  b   c
  #3 10    10  f    

或使用aggregatestr_split_fixed

 res1 <- aggregate(.~ V1, data=dat, FUN=function(x) paste(sort(x), collapse=","))
 library(stringr)
 res1[, paste0("V", 3:4)] <- as.data.frame(str_split_fixed(res1$V3, ",", 2), 
                                              stringsAsFactors=FALSE)

如果您需要NA以獲取缺失值

  res1[res1==''] <- NA
  res1
  # V1    V2 V3   V4
 #1  1 1,2,4  a  d,e
 #2  2   3,5  b    c
 #3 10    10  f <NA>

數據

dat <- structure(list(V1 = c(1L, 2L, 2L, 1L, 1L, 10L), V2 = c(1L, 3L, 
5L, 4L, 2L, 10L), V3 = c("a", "b", "c", "d", "e", "f")), .Names = c("V1", 
"V2", "V3"), class = "data.frame", row.names = c(NA, -6L))

這是一種使用data.table的方法,其中的數據來自@akrun的帖子:

將列存儲為list而不是將它們粘貼在一起可能會很有用。

require(data.table) ## 1.9.2+
setDT(dat)[order(V1, V2), list(V2=list(V2), V3=V3[1L], V4=list(V3[-1L])), by=V1]
#    V1    V2 V3  V4
# 1:  1 1,2,4  a e,d
# 2:  2   3,5  b   c
# 3: 10    10  f    

setDT(dat)通過引用將data.frame轉換為data.table(不進行復制)。 然后,我們對已排序數據按V1,V2列進行排序,並按V1列進行分組,並為每個組創建如圖所示的V2V3V4列。

V2V4將在此處list類型。 如果您希望將所有條目都粘貼在一起的字符列,只需將list(.)替換為paste(., sep=...)

高溫超導

暫無
暫無

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

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