0

I am working with some data in R. My task is to get the sum of all rows in different datasets of a list. This is the data:

#Data
mylist <- list(a=data.frame(v1=1:3,v2=3:1),
               b=data.frame(v1=19:21,v2=23:21),
               c=data.frame(v1=letters[1:3],v2=1:3,v3=3:1),
               d=data.frame(v1=1:8,v2=8:1,v3=letters[1:8]),
               e=data.frame(v1=9:1,v2=19:27))

Then I have a loop (please avoid any other kind of solution as my real data uses a similar structure):

#Loop
for(i in 1:length(mylist))
{
  x <- mylist[[i]]
  for(j in 1:dim(x)[1])
  {
    rowSums(x[j,])
    print(paste(i,j))
  }
}

I have included character variables so that it returns error. I want to understand how to place a trycatch in the loop so that instead of getting the loop stopped like this:

[1] "1 1"
[1] "1 2"
[1] "1 3"
[1] "2 1"
[1] "2 2"
[1] "2 3"
Error in rowSums(x[j, ]) : 'x' must be numeric

I can get a message like Error in 2 4 and then continue until all sums can be computed.

Many thanks.

user007
  • 347
  • 1
  • 3
  • 12
  • What exactly is the desired output for this sample input? Are you really just printing values to the console? And you just want to not print an error? Did you try to use `tryCatch` at all yet? What did you try and where did you get stuck? Doing an explicit double loop can be very inefficient especially since `rowSums` is already vectorized. It doesn't make sense to loop over each row. – MrFlick May 01 '23 at 14:54
  • Have you had a look at the excellent [FAQ, How to write `tryCatch` in R?](https://stackoverflow.com/a/12195574/903061). Pretty much directly following the answer there, something like `tryCatch( expr = { rowSums(x[j,]) print(paste(i,j)) }, error=function(cond) { message(sprintf("Error in the loop on i = %s, j = %s", i, j)) message(" Here's the original error message:") message(cond) } )` should work. (Apologies for comment formatting) – Gregor Thomas May 01 '23 at 14:58
  • I'd also add that if you find `tryCatch` difficult, you may prefer the function `purrr::safely`, or its variants `quietly` and `possibly`. – Gregor Thomas May 01 '23 at 15:04

0 Answers0