在R语言中对多列计算累积和并生成Pre前缀变量的技术问询
Hey there! Let's work through creating those PreYYYY cumulative sum variables for your dataset. Here's a couple of straightforward approaches that fit your needs:
First, Let's Recap Your Data Setup
First, let's confirm your initial data and renaming step (since R automatically prepends X to column names that start with numbers):
# Define your original dataset test <- data.frame("1991" = c(1,5,3), "1992" = c(4,3,3), "1993" = c(10,5,3), "1994" = c(1,1,1), "1995" = c(2,2,6)) # Rename columns to remove the auto-added X prefix test <- plyr::rename(test, c("X1991"="1991", "X1992"="1992", "X1993"="1993", "X1994"="1994", "X1995"="1995"))
Approach 1: Base R (No Extra Packages Needed)
If you prefer sticking to base R, you can use apply to calculate row-wise cumulative sums, then rename the columns and merge back to your original data:
# Calculate row-wise cumulative sums cumulative_values <- t(apply(test, 1, cumsum)) # Add the "Pre" prefix to column names colnames(cumulative_values) <- paste0("Pre", colnames(test)) # Merge the cumulative columns into your original data frame test <- cbind(test, cumulative_values)
Approach 2: Using dplyr (More Intuitive Syntax)
If you're open to using the dplyr package (part of the tidyverse), this method is cleaner and more readable:
library(dplyr) # Add cumulative sum columns with the "Pre" prefix directly test <- test %>% mutate(across(everything(), cumsum, .names = "Pre{col}"))
What This Does
Both methods will generate exactly what you need:
Pre1991=test$1991(since it's the first year, cumulative sum is just the value itself)Pre1992=test$1991 + test$1992Pre1993=test$1991 + test$1992 + test$1993- And so on for the remaining years
Quick Check of the Result
If you print test after running either method, you'll see the new cumulative columns:
print(test) # 1991 1992 1993 1994 1995 Pre1991 Pre1992 Pre1993 Pre1994 Pre1995 # 1 1 4 10 1 2 1 5 15 16 18 # 2 5 3 5 1 2 5 8 13 14 16 # 3 3 3 3 1 6 3 6 9 10 16
内容的提问来源于stack exchange,提问作者Data Science Beginner

