There is dataframe ori_df , how to rowsum it avoid error message or in a smart way ? refer below seqarately question 1 \question 2
ori_df <- data.frame(values = 1:10) %>% t() %>% as.data.frame()
colnames(ori_df) <- LETTERS[1:10]
map_list <- list('group_a' = c('A','D','E'),'group_b' = c('G','H','Z'))
question 1: There is no varialbe Z
in ori_df
, how to avoid error and show group_b
equal G
+ H
(How to fix below code?)
group_df <- ori_df %>% mutate(group_a = A + D + E,
group_b = G + H + Z)
question 2: How to create varialbes group_a
, group_b
,according map_list
and avoid the error which Z
not in variables of ori_df
(How to fix below code?)
group_df <- ori_df %>% rowwise() %>% mutate(sum=sum(c_across(map_list)))
You can try
cbind(
ori_df,
lapply(
map_list,
\(x) sum(t(ori_df)[match(x, names(ori_df)), ], na.rm = TRUE)
)
)
which gives
A B C D E F G H I J group_a group_b
values 1 2 3 4 5 6 7 8 9 10 10 15