问题
My data.frage looks like this:
VAR1 VAR2 AUS1 AUS2 AUS3 AUS4 ... AUS56 VAR3 VAR4
A D 23 234 34 856 ... 99 0 FCK
B D 55 76 55 36 ... 6456 0 XYC
I'd like R to add a new variable AUS which shows the rowsums of the variables AUS1 to AUS56, preferably with dplyr. AUS1 to AUS56 can then be deleted.
回答1:
You can try use rowSums in combination with grep:
df %>% mutate(AUS_sum = rowSums(.[grep("AUS", names(.))]))
回答2:
Here is another option using tidyverse syntax
library(tidyverse)
df1 %>%
select(matches("AUS")) %>%
reduce(`+`) %>%
mutate(df1, AUS_sum = .)
# VAR1 VAR2 AUS1 AUS2 AUS3 AUS4 AUS56 VAR3 VAR4 AUS_sum
#1 A D 23 234 34 856 99 0 FCK 1246
#2 B D 55 76 55 36 6456 0 XYC 6678
With the devel version of dplyr (soon to be released 0.6.0) we can create a function with quosures and make it more dynamic. Here, the enquo does similar functionality as substitute from base R by taking the input arguments and converting it to quosure, with quo_name, we convert it to string where matches takes string argument. The lhs name can also be created as string ('newN') and within the mutate/summarise/group_by, we unquote (!! or UQ) to evaluate the string
fSum <- function(dat, pat){
pat <- quo_name(enquo(pat))
newN <- paste0(pat, "_sum")
newSum <- dat %>%
select(matches(pat)) %>%
reduce(`+`)
dat %>%
mutate(!!newN := newSum)
}
fSum(df1, AUS)
# VAR1 VAR2 AUS1 AUS2 AUS3 AUS4 AUS56 VAR3 VAR4 AUS_sum
#1 A D 23 234 34 856 99 0 FCK 1246
#2 B D 55 76 55 36 6456 0 XYC 6678
Based on the OP's comment on the other post about removing the columns that used for sum, we can modify the function
fSumN <- function(dat, pat){
pat <- quo_name(enquo(pat))
newN <- paste0(pat, "_sum")
newSum <- dat %>%
select(matches(pat)) %>%
reduce(`+`)
dat %>%
select(-matches(pat)) %>%
mutate(!!newN := newSum)
}
fSumN(df1, AUS)
# VAR1 VAR2 VAR3 VAR4 AUS_sum
#1 A D 0 FCK 1246
#2 B D 0 XYC 6678
data
df1 <- structure(list(VAR1 = c("A", "B"), VAR2 = c("D", "D"), AUS1 = c(23L,
55L), AUS2 = c(234L, 76L), AUS3 = c(34L, 55L), AUS4 = c(856L,
36L), AUS56 = c(99L, 6456L), VAR3 = c(0L, 0L), VAR4 = c("FCK",
"XYC")), .Names = c("VAR1", "VAR2", "AUS1", "AUS2", "AUS3", "AUS4",
"AUS56", "VAR3", "VAR4"), class = "data.frame", row.names = c(NA,
-2L))
回答3:
In base R:
df$AUS <- rowSums(df[,grep('AUS', names(df))])
来源:https://stackoverflow.com/questions/43515925/rowsums-conditional-on-column-name