Hello to Rusers!
I am puzzled with R and I really do not know where to look
in for my problem. I am moving from SAS and I have difficulties
in translating SAS to R world. I hope I will get some hints or pointers so I can study from there on.
I would like to do something like this. In SAS I can write a macro as example bellow, which is afcourse a silly one but shows what I don't know how to do in R.
%macro test(data, colname, colvalue); data &data; ... &colname="&colvalue"; other_&colname="other_&colvalue"; run; %mend;
And if I run it with this call: %test(Gregor, Gorjanc, 25);
I get a table with name 'Gregor' and columns 'Gorjanc', and 'other_Gorjanc' with values:
Gorjanc other_Gorjanc "25" "other_25"
So can one show me the way to do the same thing in R?
Thanks!
-- Lep pozdrav / With regards, Gregor GORJANC
Greetings, Gregor, from a fan of Slovenia.
Here is a start. Multiple variables are often put together in data frames. Your example did not include an input dataset name. I took data to be an input data frame, and added two new variables. I assume that colvalue and colname are character values. If colvalue has length one it will be duplicated for each row of data.
test <- function(data, colname, colvalue) { data[[colname]] <- colvalue data[[paste('other',colname,sep='_')]] <- paste('other',colvalue,sep='_') data }
Example usage:
data <- data.frame(x=1:5, y=11:15)
data2 <- test(data, 'a', 'b')
data <- test(data, 'a', 'b') # over-write
test(data, 'a', 'b') # create data but don't store
with(test(data, ....),{...}) # reference variables in temporary dataset
If we know what your ultimate goal is, there may be a much better approach than the test function. In many cases, you do not need to create new variables at all.
Franc -- Frank E Harrell Jr Professor and Chair School of Medicine Department of Biostatistics Vanderbilt University
______________________________________________ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html