On 26-09-2012, at 12:49, jeff6868 <geoffrey_kl...@etu.u-bourgogne.fr> wrote:
> Hi everyone, > > I have a small problem in my R-code. > > Imagine this DF for example: > > DF <- data.frame(number=c(1,4,7,3,11,16,14,17,20,19),data=c(1:10)) > > I would like to add a new column "Station" in this DF. This new column must > be automatically filled with: "V1" or "V2" or "V3". > The choice must be done on the numbers (1st column). > > For example, I would like to have "V1" in the column "Station" in the rows > where the numbers of the 1st column are: 1,7,11,16 ; then I would like to > have "V2" in the rows where the numbers are: 4,14,20 and finally "V3" in the > rows where the numbers are: 3,17,19. > > I'm trying with "if" and something like this, but it's not working yet: > # For "V1": > if(DF$number %in% c(1,7,11,16)) {test$Station=="V1"} > # For "V2": > ... > > So my final DF should look like this: > > FINALDF <- data.frame(number=c(1,4,7,3,11,16,14,17,20,19),data=c(1:10), > Station=c("V1","V2","V1","V3","V1","V1","V2","V3","V2","V3")) > DF[DF$number %in% c(1,7,11,16),"Station"] <- "V1" DF[DF$number %in% c(4,14,20),"Station"] <- "V2" DF[DF$number %in% c(3,17,19),"Station"] <- "V3" DF The Station column is of type character. To make FINALDF identical you should add stringsAsFactors=FALSE to the arguments of data.frame. Berend ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.