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.