粘贴多列(奇怪的行为)

时间:2017-03-06 18:36:30

标签: r

我试图将几个具有相同名称的列粘贴到一个新行中但我得到了一些奇怪的行为。例如:

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 个答案:

答案 0 :(得分: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
相关问题