Skip to content
Prev 51792 / 398500 Next

Calculate correctly, but gives an error message

Hi!

I will calculate sum??s in the following way:
E.g.: 


a <- rpois(100,20)
b <- rpois(100,5)

x <- data.frame(cbind(a,b))

# the sum??s should be calculated based on a.

attach(x) 

sort.nace <- unique(sort(x[,1]))

sum1 <- matrix(ncol=1, nrow=length(sort.nace))

# I calculate the sum of all values of b, which have the same category in a. Eg.:

sum1[1,] <- sum(subset(x, a==sort.nace[1], select=b), na.rm=TRUE)

# or:

sum1[5,] <- sum(subset(x, a==sort.nace[5], select=b), na.rm=TRUE)

# all is ok.
# but when I do it in a loop, I get an error message.

sum1 <- matrix(ncol=1, nrow=length(sort.nace))
for(i in 1:length(nace)){
	sum1[i,] <- sum(subset(x, a==sort.nace[i], select=b), na.rm=TRUE)
	}
#Error in Summary.data.frame(..., na.rm = na.rm) : 
#        only defined on a data frame with all numeric or complex variables

# but sum1 was correct calculated(!):

# sum1
#       [,1]
#  [1,]    3
#  [2,]    4
#  [3,]    8
#  [4,]    7
#  [5,]   41
#  [6,]   57
#  [7,]   38
#  [8,]   15
#  [9,]   44
# [10,]   72
# [11,]   57
# [12,]   27
# [13,]   12
# [14,]   24
# [15,]   29
# [16,]   16
# [17,]   19
# [18,]    3
# [19,]    4
# [20,]    8
# [21,]    6

The variables of x are of class numeric. 
My function, which should calculate these sum??s, does not work, because of this error.

Can anybody please tell me, what I??m doing wrong?

(I think it would be better to write a sapply instead of the loop, but I have two functions (sum and subset) and it is very hard for me to use the sapply here correctly)

Thanks,
Matthias