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])]