2

I have the name of a matrix as string and would like to assign to a column of that matrix.

A <- matrix(1:4,2)
v <- 10:11
name <- "A"
get(name)[,2] <- v

This does not work because the LHS is just a value (i.e. a vector) and has lost the meaning of "the second column of A".

eval(parse(text=paste0(name,'[,2]<- v')))

This does the job, but a lot of people discourage the use of such a structure. What is the recommended way to go about this?

EDIT: Most comments on similar problems I have found discourage the use of object names that can only be passed as strings and instead promote the use of lists, i.e.

l <- list(A=matrix(1:4,2))
v <- 10:11
name <- "A"
l[[name]][,2] <- v

but this does not really answer my question.

user1965813
  • 671
  • 5
  • 16
  • 1
    you should make your question more clear –  Mar 04 '15 at 10:11
  • 2
    If you convert the matrix to dataframe, you would be able to use `assign` i.e. `A <- as.data.frame(A); assign(name, '[[<-'(get(name), 'V2', value=v))` – akrun Mar 04 '15 at 10:23
  • 1
    If you really have to... `assign(name, {B <- get(name); B[,2] <- v; B})` – bergant Mar 04 '15 at 10:27
  • Thank you both for your solutions. Both use a intermediate assignment to solve it. I think I could adapt something of the kind to my problem. – user1965813 Mar 04 '15 at 11:30

1 Answers1

0

For changing names of columns, you should work on a data.frame and not on a matrix:

A <- matrix(1:4,2)
v <- 10:11
name <- "A"

A <- as.data.frame(A)
v <- as.data.frame(v)
colnames(A)[2] <- name
A[,2] <- v

Is this what you were looking for?

jeff6868
  • 163
  • 1
  • 2
  • 9
  • 1
    I do not want to have a named column. Instead I want to avoid having to use the name in the assignment. (I.e. no "A" in the actual replacement of the column, just a reference to "name") – user1965813 Mar 04 '15 at 11:24