2012/08/21

R tips: inserting factor value into data frame

Here is sample R script for inserting factor value into data frame.
> data <- data.frame(iris)
> cind <- length(data) + 1
> data[data$Species == 'setosa', cind] <- c('setosa')
> data[data$Species != 'setosa', cind] <- c('vervir')
> data[,cind] <- as.factor(data[,cind])
> names(data)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"     
[6] "V6"          
> names(data)[6]
[1] "V6"
> names(data)[6] <- c('Species2')

No comments:

Post a Comment

100