如何将多列二进制调查数据合并为单列(任意列含1则结果为1)
Hey there! Let's work through how to collapse your 3 survey columns into one binary column where a row gets a 1 if any of the three surveys in that year was 1, and 0 only if all three are 0.
First, let's confirm your data structure: you have a 3D array with 4 observations (rows), 3 surveys per year (columns), and 4 years (slices). Let's start by looking at a sample of your data to make sure we're on the same page:
# Your original data x <- structure(c(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1), .Dim = c(4L, 3L, 4L)) # Check the first year's survey data x[,,1]
This outputs:
[,1] [,2] [,3] [1,] 0 0 0 [2,] 1 1 1 [3,] 0 0 0 [4,] 1 1 1
The Simple Solution
Since your values are only 0 and 1, taking the maximum of each row's 3 survey values will give exactly what you need: max(0,0,0) = 0, and max(1, ...) = 1. We can use apply() to run this calculation across each row and year slice:
# Collapse columns using max() collapsed_result <- apply(x, c(1, 3), max) # Alternatively, use any() for more explicit logic (does the row have any 1s?) collapsed_result <- apply(x, c(1, 3), function(row) as.integer(any(row == 1)))
What This Does
apply(x, c(1, 3), max): Thec(1,3)tells R to operate across the 1st dimension (observations/rows) and 3rd dimension (years/slices). For every combination of row and year, it takes the max of the 3 survey values.- The
any()version is more readable if you want to explicitly state the rule: it checks if any value in the row is 1, then converts that TRUE/FALSE to 1/0 withas.integer().
The Result
Running either code will give you a 4x4 matrix where each cell represents an observation's annual result:
print(collapsed_result)
Output:
[,1] [,2] [,3] [,4] [1,] 0 1 1 1 [2,] 1 1 1 1 [3,] 0 1 1 1 [4,] 1 1 1 1
If you need to reshape this into a single vector instead of a matrix, you can use as.vector(collapsed_result) or c(collapsed_result)—just keep in mind the order will be all rows for year 1, then year 2, etc.
内容的提问来源于stack exchange,提问作者KimChiya

