将R中具有相同名称的列分组
如果我有一个如下的数据框,第一行是列名(这里不包括行名) 我如何才能创建一个新的数据框架,以便:将R中具有相同名称的列分组,r,R,如果我有一个如下的数据框,第一行是列名(这里不包括行名) 我如何才能创建一个新的数据框架,以便: a b c 1 2 3 4 6 7 5 NA 8 NA NA 9 注意NA。对于空值 更新 If d.frame is the dataframe in question: new.df <- data.frame(); firstrow <- d.frame[,1] names <- unique(firstrow) for (n
a b c
1 2 3
4 6 7
5 NA 8
NA NA 9
注意NA。对于空值
更新
If d.frame is the dataframe in question:
new.df <- data.frame();
firstrow <- d.frame[,1]
names <- unique(firstrow)
for (n in names) {
#cbind.fill is part of a package plyr
new.df <- cbind.fill(new.df, frame[3,which(firstrow == n)])
}
colnames(new.df) <- names;
如果d.frame是有问题的数据帧:
new.df找不到一个简单的解决方案,所以这里有一个选项,按照您在评论中的要求使用base R。无论原始数据中有多少列,此解决方案都有效
temp <- read.table(text = "A B C D E F G H I
a b c a a b c c c
1 2 3 4 5 6 7 8 9", header = T) # your data
temp <- data.frame(t(temp))
lengths <- table(temp[, 1])
maxval <- max(lengths)
data.frame(do.call(cbind, lapply(levels(temp[, 1]), function(x) c(x, temp[temp[, 1] == x, 2], rep(NA, maxval - lengths[x])))))
## X1 X2 X3
## 1 a b c
## 2 1 2 3
## 3 4 6 7
## 4 5 <NA> 8
## 5 <NA> <NA> 9
temp这是另一个解决方案,基于函数cbind.fill
from
cbind.fill我将t
传输原始的两行data.frame
,创建一个“time”变量,使用重塑
重新组织数据,并t
传输结果
像这样:
x <- t(mydf)
y <- data.frame(cbind(x, ave(x[, 1], x[, 1], FUN = seq_along)))
t(reshape(y, direction = "wide", idvar = "X1", timevar = "X3"))
# A B C
# X1 "a" "b" "c"
# X2.1 "1" "2" "3"
# X2.2 "4" "6" "7"
# X2.3 "5" NA "8"
# X2.4 NA NA "9"
x这里的数据结构是两行和两列A到I?我想确保我能理解。是的,很抱歉解释得不好。我想我也许能用几行代码把一些东西拼凑起来。也许是这样的(参见更新部分)c 9组合在哪里?哇,我失败了。给我一秒钟。与其说是基于,不如说是直接抄袭。逐字的你不应该把OP指向那个答案吗?@SimonO'Hanlon,重定向的答案看起来怎么样?您是否期望这样的回答:“使用Split(df[2,],df[1,])
拆分数据,然后使用cbind.fill()
”?问题完全不同,split
实际上是解决这个问题的好方法。好的,我添加了另一个解决方案,完全基于split
和sapply
。可能这不是最好的方法,存在一种更优雅的方法。对我来说,使用split
来完成这项任务看起来很自然。棒极了,效果很好。我只想做一个无关紧要的小修正,以消除恼人的警告信息。在data.frame()函数中,只需添加row.names=NULL作为参数。老实说,无论哪种方式,代码都是功能性的,但我不希望看到红色:D
cbind.fill<-function(...){
nm <- list(...)
nm<-lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function (x)
rbind(x, matrix(, n-nrow(x), ncol(x)))))
}
df <- read.table(text = "A B C D E F G H I
a b c a a b c c c
1 2 3 4 5 6 7 8 9", header = T, as.is=T)
df <- as.matrix(df)
do.call(cbind.fill, split(df[2,], df[1,]))
df <- as.matrix(df)
lst <- split(df[2,], df[1,])
m <- max(sapply(lst, length))
result <- sapply(lst, function(x) {length(x) <- m; x})
x <- t(mydf)
y <- data.frame(cbind(x, ave(x[, 1], x[, 1], FUN = seq_along)))
t(reshape(y, direction = "wide", idvar = "X1", timevar = "X3"))
# A B C
# X1 "a" "b" "c"
# X2.1 "1" "2" "3"
# X2.2 "4" "6" "7"
# X2.3 "5" NA "8"
# X2.4 NA NA "9"