Home > Enterprise >  Double for loops in R and Python
Double for loops in R and Python

Time:01-02

I am trying to convert the double for loops in Python in R. It works properly when I use it inside the paste function. I am trying to figure out why are these not accessible without it.

In Python

l1 = ['appetizer','main course']
l2 = ['italian','mexican','french']

for i in l1:
    for j in l2:
        print(i,j)

In R

l1 = list('appetizer','main course')
l2 = list('italian','mexican','french')

This throws an error

for (i in l1) {
  for (j in l2) {
    print(i,j)
  }
}

Error

Error in print.default(i, j) : invalid 'digits' argument
In addition: Warning message:
In print.default(i, j) : NAs introduced by coercion
> for (i in l1) {

This doesn't throw an error

for (i in l1) {
  for (j in l2) {
    print(paste(i,j,sep=","))
  }
}

Output

[1] "appetizer,italian"
[1] "appetizer,mexican"
[1] "appetizer,french"
[1] "main course,italian"
[1] "main course,mexican"
[1] "main course,french"

CodePudding user response:

There is a difference between indexing. While Python passes vectors (arrays) as indices, R passes the values. Note that the indices start with 1, i.e. 1, 2, ..., n. You also need to concatenate the objects you want to print, to pass them as a single argument. Accordingly you could do something like this:

l1 <- list('appetizer', 'main course')
l2 <- list('italian', 'mexican', 'french')

for (i in seq_along(l1)) {
  for (j in seq_along(l2)) {
    print(c(l1[[i]], l2[[j]]))
  }
}
# [1] "appetizer" "italian"  
# [1] "appetizer" "mexican"  
# [1] "appetizer" "french"   
# [1] "main course" "italian"    
# [1] "main course" "mexican"    
# [1] "main course" "french"  

CodePudding user response:

See this below explaination of the print method.

print(x, digits = NULL, quote = TRUE,
  na.print = NULL, print.gap = NULL, right = FALSE,
  max = NULL, useSource = TRUE, …)

x       the object to be printed.

digits  a non-null value for digits specifies the minimum number of 
        significant digits to be printed in values. The default, NULL, uses 
        getOption("digits"). (For the interpretation for complex numbers see 
        signif.) Non-integer values will be rounded down, and only values 
        greater than or equal to 1 and no greater than 22 are accepted.
...

Apparently the second variable is not accepted as valid parameter.

While this is a little odd, the more important point is that print(a,b) is not a syntactically correct way to print multiple values.

so you can proceed to use paste() function

or indexes like print(c(l1[[i]], l2[[j]]))

  • Related