我正在尝试合并列并计算具有相同定义字符串模式的行总和。
例如:
mat <- matrix( 1:20, nrow = 2, ncol = 10, byrow = TRUE)
colnames(mat) <- c("slurry","slurrys","liquid","liquids","solut","solution","aqueou","aqueous","agent","agents")
mat
slurry slurrys liquid liquids solut solution aqueou aqueous agent agents
[1,] 1 2 3 4 5 6 7 8 9 10
[2,] 11 12 13 14 15 16 17 18 19 20
我想得到以下结果:
slurry liquid solut aqueou agent
[1,] 3 7 11 15 19
[2,] 23 27 31 35 39
我尝试过使用sapply,但计算结果是错误的。
nams <- c("slurry", "liquid", "solut","aqueou", "agent")
nams_bind <- sapply(nams, function(i)rowSums(mat[, nams==i, drop=FALSE]))
nams_bind
slurry liquid solut aqueou agent
[1,] 7 9 11 13 15
[2,] 27 29 31 33 35
有什么方法可以修改它吗?
答案 0 :(得分:1)
我们可以使用grep
根据模式对列进行子集,因为==
会查找完全匹配
sapply(nams, function(x) rowSums(mat[,grep(x, colnames(mat))]))
# slurry liquid solut aqueou agent
#[1,] 3 7 11 15 19
#[2,] 23 27 31 35 39