如果列名称匹配模式,则将特定列中的所有值相乘

时间:2014-08-19 14:13:26

标签: regex r

如果列名与模式匹配,我想使某些列中的所有值为负(乘以-1)。

我的数据:

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

我想将包含'start'的所有列转换为负数。

由于

-al

编辑1:

我还想创建两个新列(df$startdf$end),它们分别是包含“start”和“end”的所有列的总和。

2 个答案:

答案 0 :(得分:5)

df[,grep("start", names(df))] <- df[,grep("start", names(df))] * -1

答案 1 :(得分:1)

针对您的edited问题

 within(df, {start <- rowSums(df[,grep("start", names(df))])
             end <- rowSums(df[,grep("end", names(df))])} )