按列名称划分每个单元格

时间:2019-12-29 16:09:35

标签: r

我想将每个值除以各自的列名。

enter image description here

如您在图像中看到的-列名称为0、1、2、3

R代码产生数据帧:

structure(list(Variables = c("Orig_year", "Orig_year", "Orig_year", 
"Orig_year", "Orig_year", "Orig_year", "Sales.Channel", "Sales.Channel", 
"Sales.Channel", "Sales.Channel"), Categories = c("2014", "2015", 
"2016", "2017", "2018", "2019", "Brokers", "Lead Generators", 
"Major Dealers", "Middle Market"), `0` = c(0, 0, 0.0000533134296529296, 
0.000100515982041145, 0.000104958226625803, 0, 0.0000981763738556316, 
0, 0.000052988554472234, 0.0000555957080113415), `1` = c(0, 0.000465549348230912, 
0.000373194007570507, 0.000402063928164578, 0.000272891389227088, 
0.000103053828449727, 0.000343617308494711, 0, 0.000211954217888936, 
0.000277978540056708), `2` = c(0, 0.0010862818125388, 0.000853014874446873, 
0.000938149165717349, 0.000650741005079978, 0.000137405104599636, 
0.000662690523525514, 0, 0.00052988554472234, 0.000681047423138934
)), row.names = c(NA, -10L), class = "data.frame")

2 个答案:

答案 0 :(得分:1)

nms是一个向量,其中包含具有数字的列的名称。通过重复nrow(DF)次,我们将这些列除以该数字。我们用它替换每个这样的列。不使用任何软件包。

nms <- grep("\\d", names(DF), value = TRUE)
replace(DF, nms, DF[nms] / rep(as.numeric(nms), each = nrow(DF)))

给予:

       Variables      Categories   0            1            2
1      Orig_year            2014 NaN 0.0000000000 0.000000e+00
2      Orig_year            2015 NaN 0.0004655493 5.431409e-04
3      Orig_year            2016 Inf 0.0003731940 4.265074e-04
4      Orig_year            2017 Inf 0.0004020639 4.690746e-04
5      Orig_year            2018 Inf 0.0002728914 3.253705e-04
6      Orig_year            2019 NaN 0.0001030538 6.870255e-05
7  Sales.Channel         Brokers Inf 0.0003436173 3.313453e-04
8  Sales.Channel Lead Generators NaN 0.0000000000 0.000000e+00
9  Sales.Channel   Major Dealers Inf 0.0002119542 2.649428e-04
10 Sales.Channel   Middle Market Inf 0.0002779785 3.405237e-04

尽管通常情况下覆盖对象不是一个好主意,但是在这种情况下可以接受replace行的写法:

DF[nms] <- DF[nms] / rep(as.numeric(nms), each = nrow(DF))

有关其他选择,请参见本文的data.frame部分:How to divide each row of a matrix by elements of a vector in R

答案 1 :(得分:1)

如果要换位,则该除法应该可以按预期进行:

cbind(df[,1:2], t(t(df[, -(1:2)]) / as.numeric(names(df[, -(1:2)]))))
       Variables      Categories   0            1            2
1      Orig_year            2014 NaN 0.0000000000 0.000000e+00
2      Orig_year            2015 NaN 0.0004655493 5.431409e-04
3      Orig_year            2016 Inf 0.0003731940 4.265074e-04
4      Orig_year            2017 Inf 0.0004020639 4.690746e-04
5      Orig_year            2018 Inf 0.0002728914 3.253705e-04
6      Orig_year            2019 NaN 0.0001030538 6.870255e-05
7  Sales.Channel         Brokers Inf 0.0003436173 3.313453e-04
8  Sales.Channel Lead Generators NaN 0.0000000000 0.000000e+00
9  Sales.Channel   Major Dealers Inf 0.0002119542 2.649428e-04
10 Sales.Channel   Middle Market Inf 0.0002779785 3.405237e-04