我有一个data.frame有几个变量,我需要根据它们名称中的模式求和.更具体地说,我有总共一个的股票,不包括我需要找到的可能残差.我正在使用dplyr这个.
示例data.frame:
df <- data.frame(year = c(2000, 2001, 2002),
aShare = c(.1,.2,.3),
bShare = c(.3,.4,.5))
Run Code Online (Sandbox Code Playgroud)
我试过用这样的ends_with函数:
tmp <- df %>% mutate(otherShare = 1 - sum(ends_with("Share")))
Run Code Online (Sandbox Code Playgroud)
但它不会产生所需的结果:
TMP <- df %>% mutate(otherShare = 1 - (aShare + bShare))
Run Code Online (Sandbox Code Playgroud)
基地R
df$x <-1- rowSums(df[colnames(df)[grepl("Share",colnames(df))]])
Run Code Online (Sandbox Code Playgroud)
使用半dplyr:P
df$x = (1-df %>% select(ends_with("Share")) %>% rowSums())
Run Code Online (Sandbox Code Playgroud)