Is there a way to assign a value to a specific column within a data frame? e.g.,
dat2 = data.frame(c1 = 101:149, VAR1 = 151:200)
j = "dat2[,"VAR1"]" ## or, j = "dat2[,2]"
assign(j,1:50)
The approach above doesn't work. Neither does this:
j = "dat2"
assign(get(j)[,"VAR1"],1:50)
lets assume that we have a valid data.frame with 50 rows in each
1 . Don't use
assign
andget
if you can avoid it."dat2[,"VAR1"]"
is not valid inR
.You can also note this from the help page for
assign
A column of a data.frame is an element of a list
What you are looking for is
[[<-
If you want to assign new values to
VAR1
withindat2
,The answer to your question....
To manipulate entirely using character strings using
get
andassign
Other approaches
data.table::set
if you want to assign by reference within a
data.frame
ordata.table
(replacing an existing column only) thenset
from thedata.table
package works (even withdata.frames
)eval
andbquote
eapply
Or if you use a separate environment