I select some specific variables using grep() to do some other calculations that failed. I then created a new variable consisting of variables name and "+", not sum of the value.
# create a df
test <- data.frame(I60_freq_t = 1,
I60_freq_man = 1,
I60_freq_woman = 1,
I60_freq_lo65 = 1,
I60_freq_hi65 = 1,
I61_freq_t = 1,
I61_freq_man = 1,
I61_freq_woman = 1,
I61_freq_lo65 = 1,
I61_freq_hi65 = 1,
I62_freq_t = 1,
I62_freq_man = 1,
I62_freq_woman = 1,
I62_freq_lo65 = 1,
I62_freq_hi65 = 1
)
# extract variables with different end words and use " + " to concatenate
end_with_t <- grep('t$', names(test), value = T) %>% paste(collapse = '+')
end_with_man <- grep('[^a-z]man$', names(test), value = T) %>% paste(collapse = '+')
end_with_woman <- grep('woman$', names(test), value = T) %>% paste(collapse = '+')
end_with_lo65 <- grep('lo65$', names(test), value = T) %>% paste(collapse = '+')
end_with_hi65 <- grep('hi65$', names(test), value = T) %>% paste(collapse = '+')
# sum the value
test2 <- test %>% mutate(t = end_with_t,
man = end_with_man,
woman = end_with_woman,
lo65 = end_with_lo65,
hi65 = end_with_hi65)
# **** What I want is sum the value not sum the variables names *********
My questions are:
1.How can I revise my code to get what I want?
2.Are there better ways to do this?
Any help will be highly appreciated!!!
mutate_atand usecontains/ends/starts_withor write a function and map it to your data. What is your expected output, does collapse really sum?pastewithcollapse = "+"just creates strings with a plus character"+"between elements.t = 3