error in calculating rowsum of column having NA values

while calculating rowsum if both the column have values but getting error what i am doing wrong

df <- data.frame("T_1_1"= c(68,NA,0,105,NA,0,135,NA,24),
                 "T_1_2"=c(26,NA,0,73,NA,97,46,NA,0),
                 "T_1_3"=c(93,32,NA,103,NA,0,147,NA,139),
                 "S_2_1"=c(69,67,94,0,NA,136,NA,92,73),
                 "S_2_2"=c(87,67,NA,120,NA,122,0,NA,79),
                 "S_2_3"= c(150,0,NA,121,NA,78,109,NA,0),
                 "T_1_0"= c(79,0,0,NA,98,NA,15,NA,2)
                 
                 
)
df <- df %>% mutate(x1 = ifelse(is.na(T_1_1) & is.na(S_2_1),NA,rowSums(c(T_1_1,S_2_1),na.rm = TRUE)))
Error: Problem with `mutate()` input `x1`.
x 'x' must be an array of at least two dimensions
i Input `x1` is `ifelse(...)`.

output

T_1_1 S_2_1 x1
68 69 137
NA 67 67
0 94 94
105 0 105
NA NA NA
0 136 136
135 NA 135
NA 92 92
24 73 97

The c() function returns a one dimensional vector and that is causing the error. Here are two alternatives.

df <- df %>% mutate(x1 = ifelse(is.na(T_1_1) & is.na(S_2_1),NA,
                                rowSums(cbind(T_1_1,S_2_1),na.rm = TRUE)))

#Alternative
df <- df %>% rowwise() %>%  
  mutate(x1 = sum(T_1_1,S_2_1,na.rm = TRUE))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.