使用apply函数处理数据:基于加权规则生成新数据框
Hey there! Let's work through how to build that weighted data frame using apply() instead of the incomplete for loop you started with. First, let's recap our starting point to make sure we're on the same page.
Our Original Data Setup
First, here's the code that generates the gamematrix data frame we're working with:
set.seed(20) pay1 <- sample(1:10, 10, replace = TRUE) pay2 <- sample(1:10, 10, replace = TRUE) pay3 <- sample(1:10, 10, replace = TRUE) gamematrix <- cbind(pay1, pay2, pay3) gamematrix <- data.frame(gamematrix)
Which produces this output:
pay1 pay2 pay3 1 9 8 5 2 8 8 1 3 3 1 5 4 6 8 1 5 10 2 3 6 10 5 1 7 1 4 10 8 1 2 10 9 4 3 1 10 4 9 7
Building the Weighted Data Frame with apply()
We need to create a new data frame where each value is weighted by w = 0.5. The apply() function is perfect for this—it lets us apply a function across rows or columns of our data frame efficiently.
Here are two straightforward ways to do this:
Method 1: Using apply() Directly
We'll use apply() with MARGIN = 2 (which tells it to operate on columns) and multiply each element by our weight:
w <- 0.5 # Apply the weight function to each column, then convert back to data frame q_array <- as.data.frame(apply(gamematrix, MARGIN = 2, function(x) x * w))
If you run this, the resulting q_array will look like this:
pay1 pay2 pay3 1 4.5 4.0 2.5 2 4.0 4.0 0.5 3 1.5 0.5 2.5 4 3.0 4.0 0.5 5 5.0 1.0 1.5 6 5.0 2.5 0.5 7 0.5 2.0 5.0 8 0.5 1.0 5.0 9 2.0 1.5 0.5 10 2.0 4.5 3.5
Method 2: Using sapply() (Matching Your Initial Code Structure)
If you prefer to stick closer to the sapply() approach you started with, this works too—since data frames are lists of columns, sapply() will iterate over each column automatically:
w <- 0.5 q_array <- data.frame(sapply(gamematrix, function(x) x * w))
This gives exactly the same result as the apply() method, just using a slightly different function that's tailored for list-like structures (which data frames are under the hood).
Why This Is Better Than a for Loop
Both of these methods avoid writing a manual for loop, which makes the code shorter, more readable, and faster for larger datasets. R is built for vectorized operations, so leveraging functions like apply() and sapply() plays to its strengths.
内容的提问来源于stack exchange,提问作者YefR

