[R] replacement functions for subsets
Harry Mamaysky
h.mamaysky at gmail.com
Wed Jul 10 21:17:15 CEST 2013
As I understand it rownames(aa) returns a copy of an attribute of aa. So changing the value of this vector should make the change to the copy of the row.names attribute. I would then have to set the original row.names equal to this copy to effect the change.
So my question is why "rownames(aa)[2:4] <-" changes the original attribute rather than its copy?
And the follow on question is whether it's possible to have "f(x)[2:4] <-" operate in the same way for some user defined replacement function f.
Sent from my iPhone
On Jul 10, 2013, at 3:05 PM, David Winsemius <dwinsemius at comcast.net> wrote:
On Jul 10, 2013, at 11:47 AM, Harry Mamaysky wrote:
> I know how to define replacement functions in R (i.e. ‘foo<-‘ <- function(x,value) x<-value, etc.), but how do you define replacement functions that operate on subsets of arrays (i.e. how do you pass an index into foo)?
> For example, why does the following use of “rownames” work?
`rownames` of a dataframe is a vector, so indexing with "[" and a single vector of indices is adequate. I cannot really tell what your conceptual "why"-difficulty might be. This is just assignment within a vector. That is not really a "replacement function operating on a subset of an array" since rownames are not values of the dataframe .... and it's not an "array". (Careful use of terms is needed here.)
>
>> aa <- data.frame( a=1:10,b=101:110 )
>
>> aa
>
> a b
>
> 1 1 101
>
> 2 2 102
>
> 3 3 103
>
> 4 4 104
>
> 5 5 105
>
> 6 6 106
>
> 7 7 107
>
> 8 8 108
>
> 9 9 109
>
> 10 10 110
>
>> rownames(aa)[2:4] <- c('row2','row3','row4')
>
>> aa
>
> a b
>
> 1 1 101
>
> row2 2 102
>
> row3 3 103
>
> row4 4 104
>
> 5 5 105
>
> 6 6 106
>
> 7 7 107
>
> 8 8 108
>
> 9 9 109
>
> 10 10 110
>
>
>
>
> Thanks,
>
> Harry
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius
Alameda, CA, USA
More information about the R-help
mailing list