|
发表于 2017-2-7 13:43:21
|
显示全部楼层
想了半天,我只会循环... 【我是菜鸟】
#定义函数
featureExtend <- function(featureName,originalTable)
{
originalRange <- originalTable[,featureName]
nfeatureLevel <- nlevels(factor(originalRange))
tmp <- matrix(0,nrow=nrow(originalTable),ncol=nfeatureLevel)
colnames(tmp) <- levels(factor(originalRange))
for(colIndex in 1:nfeatureLevel)
{
tmp[which(originalRange == colnames(tmp)[colIndex]),colIndex] <- 1;
}
return(tmp)
}
# 执行函数
> cbind(original[,"A"],featureExtend("B",original),featureExtend("C",original))
# 输出 - 少了第一列的列名
B1 B2 B3 C1 C2 C3
[1,] "A1" "0" "0" "1" "1" "0" "0"
[2,] "A2" "1" "0" "0" "0" "1" "0"
[3,] "A3" "0" "0" "1" "0" "0" "1"
[4,] "A1" "0" "1" "0" "0" "0" "1"
[5,] "A3" "0" "0" "1" "0" "1" "0"
[6,] "A1" "1" "0" "0" "1" "0" "0" |
|