Brent Rawlins
Brent Rawlins

Reputation: 3

for loops in r are giving me a headache

a<-list(1:4)
for (i in a){
  print(i)
  print("should be between the numbers")
}
output:
[1] 1 2 3 4
[1] "should be between the numbers"
expected output:
[1] 1
[1] "should be between the numbers"
[2] 2
[2] "should be between the numbers"
[3] 3
[3] "should be between the numbers"
[4] 4
[4] "should be between the numbers"

Why does this happen and how can I get an output that looks closer to the expected output?

I want to be able to do something like:

list_of_data_frame_names<-list("bob","jill","jack")
list_of_data_frames<-list(bob,jill,jack)

a<-list(1:4)
for (i in a){
  q<-list_of_dataframes[[i]] %>% names() %>% length()
  b<-list(2:q)
  for (j in b){
    names(list_of_data[[i]])[j] <- paste(names(list_of_data[i]))[j], list_of_data_frame_names[i], sep="_")
}

I am working with several data sets that cover the same data but have different col names (expenses vs Expenses vs Total_Expenses for example), so I want to know which column came from which data set but don't want to do it all by hand. Note the inner loop works I have already tested it and I could just run it manually for each data set if I need to but that makes added data sets in the future harder and hard coding the same loop 8 times is hardly good coding practice.

Upvotes: 0

Views: 47

Answers (2)

Anh Nhat Tran
Anh Nhat Tran

Reputation: 562

You can modify the code as below.

a<-(1:4)
for (i in a){
  print(i)
  print("should be between the numbers")
}

#[1] 1
#[1] "should be between the numbers"
#[1] 2
#[1] "should be between the numbers"
#[1] 3
#[1] "should be between the numbers"
#[1] 4
#[1] "should be between the numbers"

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389235

You should store data in a list of length 4, right now you have data as list of length 1.

a <- as.list(1:4)
for (i in a) {
  print(i)
  print("should be between the numbers")
}

#[1] 1
#[1] "should be between the numbers"
#[1] 2
#[1] "should be between the numbers"
#[1] 3
#[1] "should be between the numbers"
#[1] 4
#[1] "should be between the numbers"

You can still use a <- list(1:4) but in which case you have to change the loop as :

for (i in a[[1]]) {
  print(i)
  print("should be between the numbers")
}

Upvotes: 3

Related Questions