Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 按变量名称汇总某些变量(列)_R_Dplyr - Fatal编程技术网

R 按变量名称汇总某些变量(列)

R 按变量名称汇总某些变量(列),r,dplyr,R,Dplyr,我想总结某些变量(数据框中的列)。 我想通过部分变量的名称来选择这些变量。 复杂的是我有各种各样的条件。因此,使用dplyr中的单个contains不起作用 以下是一个例子: ab_yy <- c(1:5) bc_yy <- c(5:9) cd_yy <- c(2:6) de_xx <- c(3:7) ab_yy bc_yy cd_yy de_xx 1 1 5 2 3 2 2 6 3 4 3 3

我想总结某些变量(数据框中的列)。 我想通过部分变量的名称来选择这些变量。 复杂的是我有各种各样的条件。因此,使用dplyr中的单个contains不起作用

以下是一个例子:

ab_yy <- c(1:5)
bc_yy <- c(5:9)
cd_yy <- c(2:6)
de_xx <- c(3:7)

  ab_yy bc_yy cd_yy de_xx
1     1     5     2     3
2     2     6     3     4
3     3     7     4     5
4     4     8     5     6
5     5     9     6     7

dat <- data.frame(ab_yy,bc_yy,cd_yy,de_xx)  
#sum up all variables that contain yy and certain extra conditions
#may look something like this: rowSums(select(dat, contains(("yy&ab")|("yy&bc")) ) )

我不认为这是最好的方法,但你可以通过grepl这样做:

rowSums(dat[,grepl(pattern = "ab.*yy|bc.*yy",colnames(dat))==T])

我不认为这是最好的方法,但你可以通过grepl这样做:

rowSums(dat[,grepl(pattern = "ab.*yy|bc.*yy",colnames(dat))==T])

编辑:已修复,抱歉,咖啡因摄入不足

如果要使用dplyr,请尝试使用
匹配项

    library(dplyr)
    dat %>%
      select(matches("*yy", )) %>%
      select(matches("ab*|bc*")) %>%
      rowSums(.)

[1]  6  8 10 12 14

编辑:已修复,抱歉,咖啡因摄入不足

如果要使用dplyr,请尝试使用
匹配项

    library(dplyr)
    dat %>%
      select(matches("*yy", )) %>%
      select(matches("ab*|bc*")) %>%
      rowSums(.)

[1]  6  8 10 12 14

使用
匹配
而不是
包含
尝试
选择_if
与所需功能使用
匹配
而不是
包含
尝试
选择_if
与所需功能thx。较短的一个:行和(dat[,grepl((ab | bc.*yy),names(dat)))是的,不错,这一个更好;)谢谢。较短的一个:行和(dat[,grepl((ab | bc.*yy),names(dat)))是的,不错,这一个更好;)