[R] Loop struggle

Chris Campbell ccampbell at mango-solutions.com
Fri Mar 9 09:37:56 CET 2012


Hi Tiff

> data1 <- data.frame(SP = c(2, 2, 1), A1 = 1:3)
> data1
  SP A1
1  2  1
2  2  2
3  1  3
> i <- 1
> data1$SP
[1] 2 2 1
> data1$SP[i]
[1] 2
> # a warning is generated when 
> # the length of the argument is 
> # greater than 1
> if(c(TRUE, TRUE, TRUE)) print("TRUE")
[1] "TRUE"
Warning message:
In if (c(TRUE, TRUE, TRUE)) print("TRUE") :
  the condition has length > 1 and only the first element will be used
> # subset by i to select element of interest
> for(i in 1:3) {
+   if(data1$SP[i] == 1)
+     data1$A1[i] <- 1
+ }
> data1
  SP A1
1  2  1
2  2  2
3  1  1


Hope this helps,

Chris

Chris Campbell
MANGO SOLUTIONS
Data Analysis that Delivers
+44 1249 705450

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of titta majasalmi
Sent: 09 March 2012 07:20
To: r-help at r-project.org
Subject: [R] Loop struggle

Hi,

I cannot get rid of  this error message:

"Warning messages:
1: In if (data$SP == 1) { :
  the condition has length > 1 and only the first element will be used
2: In if (data$SP == 1) { :
  the condition has length > 1 and only the first element will be used
3: In if (data$SP == 1) { :
  the condition has length > 1 and only the first element will be used
> data$A5
[1] 1 1 1"

The loop seems to be stuck within the first loop. I have data (in .csv
format) witch contains one example of each SP within the data, so the output should look like "123" instead of  "111". This example is simplified version just to give you the idea of the problem. What is wrong within my code? I have tried everything imaginable and cannot figure it out.

for (i in 1:n) {
if (data$SP==1){
data[1:n, "A1"]<- data$A1 <-1
data[1:n, "A2"]<- data$A2 <-1
data[1:n, "A3"]<- data$A3 <-1
data[1:n, "A4"]<- data$A4 <-1
data[1:n, "A5"]<- data$A5 <-1}
else if(data$SP==2){
data[1:n, "A1"]<- data$A1 <-2
data[1:n, "A2"]<- data$A2 <-2
data[1:n, "A3"]<- data$A3 <-2
data[1:n, "A4"]<- data$A4 <-2
data[1:n, "A5"]<- data$A5 <-2}
else if(data$SP==3){
data[1:n, "A1"]<-data$A1 <-3
data[1:n, "A2"]<-data$A2 <-3
data[1:n, "A3"]<-data$A3 <-3
data[1:n, "A4"]<-data$A4 <-3
data[1:n, "A5"]<-data$A5 <-3}

}

-Tiff

	[[alternative HTML version deleted]]

______________________________________________
R-help at 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.
LEGAL NOTICE
This message is intended for the use o...{{dropped:10}}



More information about the R-help mailing list