Warm tip: This article is reproduced from serverfault.com, please click

Problem with apply function in r: it's applied only in the first column

发布于 2020-11-28 00:03:58

I have a dataframe call indices that is result of a subset:

            X1         X2        X3        X4        X5       X6        X7        X8        X9
1    201860304  677673878  43255779 158604525  72092966 28837186  57674373  57674373 144185931
145  205140086  688684575  43958590 161181496  73264317 29305727  58611453  58611453 146528633
291  213047739  715231695  45653087 167394652  76088478 30435391  60870783  60870783 152176956
442  220164438  739123472  47178094 172986345  78630157 31452063  62904125  62904125 157260313
594  227189443  762707415  48683452 178505991  81139087 32455635  64911269  64911269 162278173

First, I don't know why after the subset, the row number shows "1, 145, 291..." instead of "1, 2, 3...".

Second, when I use

indices <- as.data.frame(apply(indices, 2, function(y) 100 * y / y[1]))

The result is:

           X1       X2       X3       X4       X5       X6       X7       X8       X9
1    100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000 100.0000
145  101.6248 101.6248 101.6248 101.6248 101.6248 101.6248 101.6248 101.6248 101.6248
291  105.5422 105.5422 105.5422 105.5422 105.5422 105.5422 105.5422 105.5422 105.5422
442  109.0677 109.0677 109.0677 109.0677 109.0677 109.0677 109.0677 109.0677 109.0677

Its the same column repetead.

How can I fix this problem?

Thanks!

Questioner
Ernesto Paredes
Viewed
0
akrun 2020-11-28 08:13:33

If we need to reset the row names

row.names(indices) <- NULL

Also, we can do this in a vectorized way

100 *indices/indices[1,][col(indices)]