R: Create 30 New Variables in a Data Frame
To create 30 new variables in a data frame in R, you can use the following code:
# Create an empty data frame
df <- data.frame()
# Create 30 new variables
for (i in 1:30) {
var_name <- paste0('var', i) # Name of the variable
var_values <- rnorm(nrow(df)) # Generate random values for the variable
df[var_name] <- var_values # Add the variable to the data frame
}
In this code, an empty data frame 'df' is created. Then, a loop is used to generate and add 30 new variables ('var1', 'var2', ..., 'var30') to the data frame. The 'var_name' variable stores the name of each new variable, and the 'var_values' variable generates random values for each variable using the 'rnorm()' function. Finally, the new variable is added to the data frame using the variable name as the column name.
原文地址: https://www.cveoy.top/t/topic/o9Mt 著作权归作者所有。请勿转载和采集!