colSums in R: 'x' must be an array of at least two dimensions

Viewed 45141

I am a beginner in coding in general. I am trying to calculate two parameters from a data frame named a in R. For row i and column j, I am interested in finding:

B = (sum of all values in column j) - a[i,j]

C = (sum of all values in row i) - a[i,j]

For i=1 , j=2, I'm writing:

  A = a[1,2]
  B = (colSums(a[1:nrow(a),1],na.rm = FALSE, dims = 1) - A)
  C = (rowSums(a[1,1:ncol(a)],na.rm = FALSE, dims = 1) - A)

C seems to give correct answer. However, B gives an error:

Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) : 
  'x' must be an array of at least two dimensions

I have read other threads as well but couldn't find my answer. Do you have any suggestions?

1 Answers

The problem is due to the command a[1:nrow(a),1]. This command selects all rows of the first column of data frame a but returns the result as a vector (not a data frame). The function colSums does not work with one-dimensional objects (like vectors).

As a side note: You don't need 1:nrow(a) to select all rows. The same is easier to achieve with an empty argument before the comma: a[ , 1].

An example data frame:

dat <- data.frame(a = 1:3, b = 4:6)
#   a b
# 1 1 4
# 2 2 5
# 3 3 6

If you select one column, the result is converted into a vector automatically.

dat[ , 1]
# [1] 1 2 3

If you specify drop = FALSE, a one-column data frame is returned.

dat[ , 1, drop = FALSE]
#   a
# 1 1
# 2 2
# 3 3

This one-column data frame is a two-dimensional object and can therefore be used with colSums.

colSums(dat[ , 1, drop = FALSE])
# a 
# 6 
Related