-1

Hello guys I am new to R, I basically got a data frame made out of 31 variables (ID, and 30 items coded 1,2,3)

I would like to create a new variable based on a specific condition.. I want to be like this:

(because 2 was present only in those 2 items(item1 and item3), so basically I want to create a new variable showing how many times 2 was selected in those 30 items)

I would really appreciate your help

Best Regards

1 Answers1

0

Thanks to MrFlick: Using Update1 version does not work as Using . in the rowSums bypasses the across() (see comment MrFlick)

Therefore we could use rowwise with c_across and sum within a dplyr workflow:

Here is an example where ID == 2:

2. Update:

data:

df <- structure(list(ID = 2L, Item1 = 2L, Item2 = 3L, Item3 = 2L, Item4 = 3L, 
    Newvariable = 2L), class = "data.frame", row.names = c(NA, 
-1L))

code:

library(dplyr)
df %>% 
    rowwise() %>% 
    mutate(Total = sum(c_across(-ID)==2))

output:

# Rowwise: 
     ID Item1 Item2 Item3 Item4 Newvariable Total
  <int> <int> <int> <int> <int>       <int> <int>
1     2     2     3     2     3           2     3

Update1: (does not work)

Using . in the rowSums bypasses the across() (see comment MrFlick)

df %>% 
    mutate(across(-ID), Total = rowSums(. == 2))

First answer:

We could use rowSums:

library(dplyr)
df %>% 
    mutate(Total = rowSums(. == 2))
  ID Item1 Item2 Item3 Item4 Newvariable Total
1  1     2     3     2     3           2     3
TarJae
  • 72,363
  • 6
  • 19
  • 66