user3421711
user3421711

Reputation: 1

How to combine different variables into one variable in R

I am trying to combine these four variables to make one new variable.

The datasets are as follows:

Collaboration_A: NA: 3, >4 times: 16, 0 times: 149, 1 time: 36, 2-4 times: 45

Collaboration_B: NA: 3, >4 times: 24, 0 times: 130, 1 time: 48, 2-4 times: 44

Collaboration_C: NA: 3, >4 times: 15, 0 times: 176, 1 time: 27, 2-4 times: 28

Collaboration_D: NA: 3, >4 times: 8, 0 times: 183, 1 time: 33, 2-4 times: 22

and I am trying to combine all of these variables to see how many students total collaborated to form the new variable "Collaboration_total"

This is the code that I input:

survey_all$collaboration_total <- 
  ifelse(survey_all$Collaboration_A>=1 &
         survey_all$Collaboration_B>=1 &
         survey_all$Collaboration_C>=1 &
         survey_all$Collaboration_D>=1, "collaborate","not collaborate")

but it is wrong. My teacher has told us to use the ifelse statement, but that is about it.

Can anyone help me with this problem?

Upvotes: 0

Views: 1661

Answers (1)

Paulo E. Cardoso
Paulo E. Cardoso

Reputation: 5856

I'm not sure I got your idea but try this

dd <- data.frame(Collaboration_A = rep(c(NA, 0, 1, 2, 5),
                                       times = c(3, 149, 36, 45, 16)),
                 Collaboration_B = rep(c(NA, 0, 1, 2, 5),
                                       times = c(3, 130, 48, 44, 24)),
                 Collaboration_C = rep(c(NA, 0, 1, 2, 5),
                                       times = c(3, 176, 27, 28, 15)),
                 Collaboration_D = rep(c(NA, 0, 1, 2, 5),
                                       times = c(3, 183, 33, 22, 8)))

dim(dd)
[1] 249   4

dd$collaboration_total <- 
  ifelse(dd$Collaboration_A>=1 &
           dd$Collaboration_B>=1 &
           dd$Collaboration_C>=1 &
           dd$Collaboration_D>=1, "collaborate","not collaborate")

Upvotes: 0

Related Questions