R error applied: "X" must have named dimnames

The "apply" documentation mentions that "where" X "called dimnames, it could be a character vector that defines dimension names." I would like to use apply on data.frame only for specific columns. Can I use dimnames function for this?

I understand that I can include a subset of () X only the columns of interest, but I want to better understand the "named dimnames".

The following is sample code:

> x <-  data.frame(cbind(1,1:10))
> apply(x,2,sum)
X1 X2
10 55
> apply(x,c('X2'),sum)
Error in apply(x, c("X2"), sum) : 'X' must have named dimnames
> dimnames(x)
[[1]]
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

[[2]]
[1] "X1" "X2"
> names(x)
[1] "X1" "X2"
> names(dimnames(x))
NULL
+5
source share
2 answers

, . , dimnames. apply data.frame . dimnames "" 1 2:

m <- matrix(1:12,4, dimnames=list(foo=letters[1:4], bar=LETTERS[1:3]))
apply(m, "bar", sum)  # Use "bar" instead of 2 to refer to the columns

, , , , :

n <- c("A","C")
apply(m[,n], 2, sum)
# A  C 
#10 42 

dimnames , dimnames dimnames matrix array. . , , ...

a data.frame "dimnames" . A data.frame , "" , "row.names" . - , dimnames ( , , ). dimnames data.frame, "row.names" "names".

+4

, - dimnames x, x , dimnames.

, , dimnames, apply()

> X <- as.matrix(x)
> str(X)
 num [1:10, 1:2] 1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:10] "1" "2" "3" "4" ...
  ..$ : chr [1:2] "X1" "X2"
> dimnames(X) <- list(C1 = dimnames(x)[[1]], C2 = dimnames(x)[[2]])
> str(X)
 num [1:10, 1:2] 1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, "dimnames")=List of 2
  ..$ C1: chr [1:10] "1" "2" "3" "4" ...
  ..$ C2: chr [1:2] "X1" "X2"
> apply(X, "C1", mean)
  1   2   3   4   5   6   7   8   9  10 
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 
> rowMeans(X)
      1   2   3   4   5   6   7   8   9  10 
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
+2

All Articles