首页 > 解决方案 > Is there an R function to combine multiple columns from the same data frame into the same column?

问题描述

At the moment I have four columns that need to be combined/merged into one column. Each row will either have four "0"s OR there will be one "1" with three "0"s.

This is what the data frame looks like right now:

id     L1_Correct    L2_Correct     L3_Correct    L4_Correct
 1          0             0              0             1
 2          1             0              0             0
 3          0             1              0             0
 4          1             0              0             0
 5          0             0              1             0

This is what I want the dataframe to look like:

 id     L1_Correct    L2_Correct     L3_Correct    L4_Correct    Combined__L_Accuracy   
 1          0             0              0             1             1
 2          1             0              0             0             1
 3          0             0              0             0             0
 4          1             0              0             0             1
 5          0             0              0             0             0

I tried using the paste function and the unite function on separate occasions: I.e,

L_Data$Combine_L_Accuracy <- paste(L_Data$L1_Correct, L_Data$L2_Correct, L_Data$L3_Correct, L_Data$L4_Correct)

L_Data_all <- L_Data %>% unite(Combine_L_Accuracy, L1_Correct, L2_Correct, L3_Correct, L4_Correct, na.rm = TRUE, remove = TRUE) 

L_Data_all

But they both provided me with an outcome like: 0_0_0_0 I only need 1 value in the last column either a 0 or 1 based on values across the four columns.

标签: rmerge

解决方案


You can use rowSums to sum all the "Correct" columns :

cols <- grep('Correct', names(L_Data))
L_Data$Combined_L_Accuracy <- rowSums(L_Data[cols])

推荐阅读