添加与模式匹配的列

时间:2014-08-19 15:46:04

标签: regex r

我想创建两个新列,其中一列(df$start)是包含短语“start”的所有列的总和,另一列(df$end)是所有列的总和包含短语'end'的列。

我的数据......

df <- structure(list(forest_closed_start = c(3.87, 1.134, 0, 1.8, 2.43, 
40.752, 22.95, 9.432, 1.89, 1.53), forest_semi_closed_start = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), shrub_start = c(0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L), forest_closed_end = c(1.935, 0, 0, 1.8, 
2.43, 0, 22.95, 0, 0, 0), forest_semi_closed_end = c(0, 0, 0, 
0, 0, 8.1504, 0, 0, 0, 1.53), shrub_end = c(0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L)), row.names = c(NA, 10L), class = "data.frame", .Names = c("forest_closed_start", 
"forest_semi_closed_start", "shrub_start", "forest_closed_end", 
"forest_semi_closed_end", "shrub_end"))

看起来像......

> df
   forest_closed_start forest_semi_closed_start shrub_start forest_closed_end forest_semi_closed_end shrub_end
1                3.870                        0           0             1.935                 0.0000         0
2                1.134                        0           0             0.000                 0.0000         0
3                0.000                        0           0             0.000                 0.0000         0
4                1.800                        0           0             1.800                 0.0000         0
5                2.430                        0           0             2.430                 0.0000         0
6               40.752                        0           0             0.000                 8.1504         0
7               22.950                        0           0            22.950                 0.0000         0
8                9.432                        0           0             0.000                 0.0000         0
9                1.890                        0           0             0.000                 0.0000         0
10               1.530                        0           0             0.000                 1.5300         0

1 个答案:

答案 0 :(得分:0)

也许使用greplrowSums可以提供帮助

ind <- grepl("start", names(df))
df$start <- rowSums(df[,ind])
df$end <- rowSums(df[,!ind])