Search code examples
rdataframelikert

How do I create a column of numeric existing data in R?


I have a data frame of 22 columns and 240 rows.

I want to create a new column with Likert Scale numeric values depending the column value.

I want to have a new column named Result with Result == 2 if one of the columns of secretary rows >= 1 else Result == 0

and Result == -2 if one of the columns of driver rows == 0 else Result == 0

the second data frame is an exemple of the result i want my code that doesn't work:

   profession ve.count.descrition euse.count.description ne.count.title
   secretary   0                      1                      2
   secretary   0                      2                      1
   driver      1                      1                      0
   driver      0                      0                      0

data <- data %>%
 for (Result in Profession){
   if(secretary [ve.count.description:ne.count.title] >= 1){
        Result == 2
   }else{Result == 0
   }
   if(driver[ve.count.description:ne.count.title] == 0){
     Result == -2
   }else{result == 0
   }
 }
mutate(result,data)

output : 
Error in for (. in result) Profession : 
 4 arguments passed to 'for' which requires 3
profession ve.count.descrition euse.count.description ne.count.title Result
secretary   0                      1                      2            2
secretary   0                      2                      1            2
driver      1                      1                      0            0
driver      0                      0                      0           -2

Solution

  • You can use case_when, like this:

        data %>%
         mutate(Result = case_when(
          profession == "secretary" & (e.count.descrition >= 1 |
                                       euse.count.description >=1 | 
                                       ne.count.title >= 1) ~ 2,
          profession == "driver" & (e.count.descrition == 0 |
                                    euse.count.description == 0 | 
                                    ne.count.title == 0) ~ -2,
          TRUE ~ 0
      ))