rrowdivide

R: Manually divide a specific row and column by a number in a dataframe


Unfortunately, I could only come across questions on how to divide columns by a specific number. However, I would like to divide the value only in a specific row and column by a number.

To illustrate, let's use the following data:

structure(list(Name = c("A", "B", "C"), Return = c(0.1, 0.5, 
0.6), Size = c(100000000000, 40030202002, 405045000000)), class = "data.frame", row.names = c("Europe", 
"Asia", "USA"))

Now how can I divide the number in row "Europe" and column "Size" by 1 million?

I know for the whole column you can do that:

Data$Size <- Data$Size /1000000

But how can I limit it only to a certain row with a given row name?


Solution

  • We can use row/column names to subset and divide

    Data["Europe", "Size"] <- Data["Europe", "Size"]/1000000
    

    -testing

    > Data$Size
    [1] 1.00000e+11 4.00302e+10 4.05045e+11
    > Data["Europe", "Size"] <- Data["Europe", "Size"]/1000000
    > Data$Size
    [1] 1.00000e+05 4.00302e+10 4.05045e+11