Skip to content

Loop struggle

3 messages · titta majasalmi, Chris Campbell, PIKAL Petr

#
Hi Tiff
SP A1
1  2  1
2  2  2
3  1  3
[1] 2 2 1
[1] 2
[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
+   if(data1$SP[i] == 1)
+     data1$A1[i] <- 1
+ }
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
[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


______________________________________________
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}}
#
Hi

you are coming from different language paradigm?

Although you did not provide your data I presume you have data frame 
called data with columns SP, A1-A5

Your construction

data[1:n, "A1"]<- data$A1 <-1

seems to me rather strange and basically your cycle shall do

data$A1<-data$A2<-data$A3<-data$A4<-data$A5<-data$SP

or if your columns were suitably located

data[,1:5] <- data$SP

If you want something else you shall provide some working example.

Regards
Petr
simplified
my
http://www.R-project.org/posting-guide.html