Steves Steves - 5 months ago 22
R Question

How to tie name to _parameter1, parameter2 to be name_parameter1 in R function?

I have function test where I have argument name. I want to "add" name to a column plus the parameter as shown here:

test <- function(name, dataframe) {
dataframe$name_parameter1 = 5
dataframe$name_parameter2 = 4

What is the way to combine name with _parameter1 _parameter2 etc?
To make it name_parameter1 etc.

(In R)

Answer Source

In R, you can use different ways to call values in a dataframe. You chose one by using $ to call a column within the dataframe.

A different way that can handle string expressions is using [row, column], where column can either be a numeric position of the column within the dataframe, or the column name as a string.

Therefore, instead of using dataframe$name_parameter1 = 5, you can use dataframe[, "name_parameter1"] = 5. And the column name can then be generated using paste(), ergo dataframe[, paste(name, "parameter1", sep = "_")], which handles your function input name (as long as it is a string).

[row, column] works with if or ifelse(), so dataframe[, paste(name, "parameter1", sep = "_")] == 4 as an if-condition is perfectly valid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download