I have this sample code to create a new data frame 'new_data' from the existing data frame 'my_data'.
new_data = NULL n = 10 #this number correspond to the number of rows in my_data conditions = c("Bas_A", "Bas_T", "Oper_A", "Oper_T") # the vector characters correspond to the target column names in my_data for (cond in conditions){ for (i in 1:n){ new_data <- rbind(new_data, c(cond, my_data$cond[i])) } }
The problem is that my_data$cond
(where cond is a variable, and not the column name) is not accepted.
How can I call a column of a data frame by using, after the dollar sign, a variable value?
The dollar sign ( $ ) and the underscore ( _ ) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code. The dollar sign ( $ ) and the underscore ( _ ) are permitted anywhere in an IdentifierName. As such, the $ sign may now be used freely in variable names.
The plus(+) sign before the variables defines that the variable you are going to use is a number variable.
Variable names can be up to 100 characters long, not including the dollar sign ($). Examples of variable names are $docname and $_currentline. Although a variable must start with a letter or underscore (_), the remainder of the name can consist of letters, digits, and underscores.
Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
To access a column, use:
my_data[ , cond]
or
my_data[[cond]]
The i
th row can be accessed with:
my_data[i, ]
Combine both to obtain the desired value:
my_data[i, cond]
or
my_data[[cond]][i]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With