Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having a data frame and in that, I am having four columns and I want to combine or merge those columns into one column. Either each row will 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 have used the paste function and the unite function on separate occasions: 

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.

1 Answer

0 votes
by (107k points)

For achieving that 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])

If you are interested in R then do check out the R programming course.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...