1
我有一個具有重複名稱的向量,我想將其轉換爲數據框,每個重複名稱都是單個列。我有一個解決方案,但肯定R提供了一個更乾淨的方式?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])]