[R] request: How to get column name

Marc Schwartz marc_schwartz at comcast.net
Wed Sep 3 17:46:35 CEST 2008


on 09/03/2008 10:34 AM Chuck Cleland wrote:
> On 9/3/2008 11:05 AM, Petr PIKAL wrote:
>> r-help-bounces at r-project.org napsal dne 03.09.2008 15:54:08:
>>
>>> try this:
>>>
>>> x <- c(3,3,3,3,0,0,0,0,5,5,5,5,8,8,8,8)
>>> x <- matrix(x, nrow=4)
>>>
>>> which(colSums(x == 0) == nrow(x))
>> Isn't this the same?
>>
>> which(colSums(x)==0)
> 
>   No, because the column sum can be zero without each element being zero:
> 
> x <- c(3,3,3,3,1,-1,1,-1,5,5,5,5,8,8,8,8)
> x <- matrix(x, nrow=4)
> 
>> which(colSums(x == 0) == nrow(x))
> integer(0)
> 
>> which(colSums(x)==0)
> [1] 2
> 

Another (column-wise) approach to this would be:

x <- c(3,3,3,3,0,0,0,0,5,5,5,5,8,8,8,8)
x <- matrix(x, nrow=4)

> which(apply(x, 2, function(i) all(i == 0)))
[1] 2


x <- c(3,3,3,3,1,-1,1,-1,5,5,5,5,8,8,8,8)
x <- matrix(x, nrow=4)

> which(apply(x, 2, function(i) all(i == 0)))
integer(0)


HTH,

Marc Schwartz



More information about the R-help mailing list