gpt4 book ai didi

r - 粘贴多列(奇怪的行为)

转载 作者:行者123 更新时间:2023-12-02 04:36:00 24 4
gpt4 key购买 nike

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

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

有人可以帮我防止这种行为吗?

最佳答案

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

关于r - 粘贴多列(奇怪的行为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com