r - Replace a part of an expression with a value from a variable -


i write expression in r can modify part of depending on other variable. example, let's want create lot of new columns in data frame using following basic expression:

mydataframe$columnnumber1 <- 33 

if wanted create lot of these, type them out explicitly

mydataframe$columnnumber2 <- 52 mydataframe$columnnumber3 <- 12 ... 

and on. however, impractical if have many of them. therefore, i'd have way of replacing part of expression that's generated through variable. let's example there operator input() this. write function looking this:

for(i in 1:1000) {     mydataframe$columnnumberinput(i) <- 32*i } 

where input(i) part replaced whatever number counter @ at moment, in turn generate expression.

i can using:

eval(parse(text=paste("mydataframe$","column","number","1","<- 32*i",sep=""))) 

but gets impossible use if expression complicated, long, or have other things nested inside of it.

use [[]]:

for(i in 1:1000) {     mydataframe[[i]] <- 32*i }  

[[]] programmatic equivalent of $.

you may reference data structure as:

mydataframe[[14]] <- mydataobjfourteen mydataframe$14 mydataframe[[14]] 

you use strings, so:

mydataframe[["somestring"]] <- 32 mydataframe$somestring # 32 

edit 1:

to similar, in more general way try:

assign("somearbitrarystring", 3) somearbitrarystring # 3 as.name(somearbitrarystring) 

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -