R将具有重复名称的命名向量转换为数据帧

时间:2016-07-18 10:18:53

标签: r vector dataframe frame

我有一个带有重复名称的向量,我想将其转换为数据帧,每个重复的名称都是一个单独的列。我有一个解决方案,但R确实提供了一种更清洁的方式吗?

#Example Input: x
x <- c(1,2,3,4,3,5,6,7)
names(x) <- c("a","b","a","b","a","b","a","b")

#Desired Output: x.desired
x.desired <- data.frame(matrix(nrow=4,ncol=2))
names(x.desired) <- c("a","b")
x.desired$a <- c(1, 3, 3, 6)
x.desired$b <- c(2, 4, 5, 7)

#Using data frame cast (doesn't work)
x.wrong <- data.frame(x)

#My solution, surely there is a cleaner way? I.e. a one line solution
colNames <- unique(names(x))
x.correct <- data.frame(matrix(nrow=length(x)/length(colNames), ncol=length(colNames)))
names(x.correct) <- colNames
for (i in 1:length(colNames))
    x.correct[,colNames[i]] <- x[which(names(x) == colNames[i])]

1 个答案:

答案 0 :(得分:1)

我们可以split names加入listcbind

do.call(cbind, split(x, names(x)))

或使用data.frame

data.frame(split(x, names(x)))