nik
nik

Reputation: 2584

how to divide all columns to specific column in a new data

I have a data like the following

df<- structure(list(S1 = c(39.2, 69.6, 1345.4, 337.5), S2 = c(43, 
64.3, 1893.2, 462.3), S3 = c(51.6, 94.8, 2198.6, 509.5), S4 = c(76.3, 
162.9, 2352.7, 555.7), S5 = c(83.9, 120.8, 3259.1, 794.8), S6 = c(91.8, 
121.1, 2823.5, 702.6), S7 = c(78, 138.4, 2878.7, 627.1), S8 = c(74.4, 
147.8, 2675.5, 699.9), S9 = c(259.6, 831.4, 4281.4, 1062.5), 
    S10 = c(85.7, 169, 3304.5, 872.7)), .Names = c("S1", "S2", 
"S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10"), row.names = 2:5, class = "data.frame")

I want to create a new data that I have the values from last column divided to the second column .....

I can do them as using the following. I am wondering if there is a better way to do it?

dftt$HS1<- df$S10/df$S2
dftt$HS2<- df$S9/df$S2
dftt$HS3<- df$S8/df$S2
dftt$HS4<- df$S7/df$S2
dftt$HS5<- df$S6/df$S2
dftt$HS6<- df$S5/df$S2
dftt$HS7<- df$S4/df$S2
dftt$HS8<- df$S3/df$S2
dftt$HS9<- dfm$S2/df$S2
dftt$HS10<- dfm$S1/df$S2



'data.frame':   335 obs. of  10 variables:
 $ S1 : num  4.1 13.7 21.3 95.1 15.7 10.7 15.6 16.4 3.9 75.8 ...
 $ S2 : chr  "13.1" "32.6" "42.7" "187.9" ...
 $ S3 : chr  "25.9" "25.6" "40" "231.4" ...
 $ S4 : num  24.3 31.4 55.4 249.4 47.6 ...
 $ S5 : num  14 72.1 102 360.2 58.8 ...
 $ S6 : chr  "11.5" "45.3" "87.5" "336.6" ...
 $ S7 : num  8 45.2 81.7 317.8 53.7 ...
 $ S8 : num  7.3 43.2 68 297 55.3 36 44.7 43 

Upvotes: 1

Views: 336

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99361

You can do this all in one line with

setNames(rev(df / df$S2), paste0("H", names(df)))
#        HS1       HS2      HS3      HS4      HS5      HS6      HS7      HS8 HS9      HS10
# 2 1.993023  6.037209 1.730233 1.813953 2.134884 1.951163 1.774419 1.200000   1 0.9116279
# 3 2.628305 12.930016 2.298600 2.152411 1.883359 1.878694 2.533437 1.474339   1 1.0824261
# 4 1.745457  2.261462 1.413216 1.520547 1.491390 1.721477 1.242711 1.161314   1 0.7106486
# 5 1.887735  2.298291 1.513952 1.356478 1.519792 1.719230 1.202033 1.102098   1 0.7300454

To set any column names you want, simply replace paste0("H", names(df)) with an appropriate character vector of names.

Upvotes: 3

Related Questions