2017-03-06 81 views
3

我想每個同名多個列粘貼到一個新行,但我得到一些奇怪的行爲。例如:粘貼多個colums(奇怪的行爲)

x <- data.frame(x = 1:10, y= 2:11, z= 11:20) 
colnames(x) <- c("x", "y", "x") 
x 
> x 
    x y x 
1 1 2 11 
2 2 3 12 
3 3 4 13 
4 4 5 14 
5 5 6 15 
6 6 7 16 
7 7 8 17 
8 8 9 18 
9 9 10 19 
10 10 11 20 
# now I try to paste columns to rows 

> x2 <- data.frame(columns = unique(colnames(x)), 
+     values = sapply(1:length(unique(colnames(x))), function(i) 
+     paste(x[,(which(unique(colnames(x))[i]==colnames(x)))], collapse = ", "))) 
> x2 
    columns       values 
1  x     1:10, 11:20 
2  y 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 

我想有的只是

> x2 
columns       values 
1  x 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 
2  y 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 

有人能幫助我阻止這種行爲?

+1

作爲一個說明,也沒有必要調用'獨特(colnames(X)) '這麼多次;你可以保存在一個變量中。另外,如果你不需要這個任務的特定格式,你可以考慮避免強制轉換爲「字符」和「粘貼」 - 聚合(cbind(values = unlist(x,use.names = FALSE))〜 rep(names(x),each = nrow(x)),FUN = c)'。最後,你傳遞的「整數」的「名單」(列命名爲「X」),以'paste'這就間接,使用該「名單」上'as.character',其結果是,因爲如何'的。 character'對待 「名單」 的參數 - 'as.character(名單(1:5))' –

+0

感謝,這是一個真正有用的解釋!我使用粘貼,因爲我的真實數據實際上是文本,但它仍然是有道理的。 – JonGrub

回答

0
x <- data.frame(x = 1:10, y= 2:11, z= 11:20) 
colnames(x) <- c("x", "y", "x") 
unique_cols <- unique(colnames(x)) 
x2 <- sapply(unique_cols, function(s) unlist(x[, unique_cols == s], use.names = F)) 
x2 

$x 
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
$y 
[1] 2 3 4 5 6 7 8 9 10 11 

typeof(x2) 
[1] "list" 

的情況下,你需要摺疊的值的數據幀:

df <- data.frame(columns = unique_cols, 
       value = as.character(sapply(x2, function(s) paste(s, collapse = ","), USE.NAMES = F))) 

df 

    columns            value 
1  x 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 
2  y        2,3,4,5,6,7,8,9,10,11 
+0

工作就像一個魅力:) – JonGrub