To create several new variables in a data frame in R, you can use the '$' operator or the 'mutate()' function from the dplyr package. Here's an example using both methods:

Method 1: Using the '$' operator

# Create a data frame
df <- data.frame(A = c(1, 2, 3),
                 B = c(4, 5, 6))

# Create new variables using the $ operator
df$C <- df$A + df$B
df$D <- df$A * df$B

# Print the updated data frame
print(df)

Method 2: Using the 'mutate()' function from the dplyr package

# Install and load the dplyr package
install.packages("dplyr")
library(dplyr)

# Create a data frame
df <- data.frame(A = c(1, 2, 3),
                 B = c(4, 5, 6))

# Create new variables using the mutate() function
df <- df %>% mutate(C = A + B,
                    D = A * B)

# Print the updated data frame
print(df)

Both methods will give you the following output:

  A B C  D
1 1 4 5  4
2 2 5 7 10
3 3 6 9 18

In both cases, we create two new variables 'C' and 'D' in the data frame 'df'. Variable 'C' is calculated by adding variables 'A' and 'B', while variable 'D' is calculated by multiplying variables 'A' and 'B'.

R: Creating Multiple New Variables in a Data Frame

原文地址: https://www.cveoy.top/t/topic/o9Mn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录