ElizaBeso000
ElizaBeso000

Reputation: 113

Divide multiple columns in a data frame by adjacent columns

I have a dataset of the mean number of animals observed in a plot with a particular dominant tree type (column names are H or B for tree type and number for plot). They are in alternating order with all H columns before B columns, like below:

Survey<-c(1,2,3)
H1<-c(5,8,3)
B1<-c(6,3,9)
H2<-c(12,15,1)
B2<-c(3,17,8)

df<-as.data.frame(cbind(Survey,H1,B1,H2,B2))

I would like to to divide each H vector by the B vector to its right (e.g. the 5 in H1/the 6 in B1, the 12 in H2/the3 in B2), but my actual dataset has 49 columns and 9 rows, so I don't want to do this manually. Is there any way to divide every other column by the column to its right?

Upvotes: 0

Views: 193

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269481

1) dplyr Use across as shown:

library(dplyr)

ix <- seq(2, ncol(df), 2)
df %>% mutate(across(ix) / across(ix+1))

giving:

  Survey        H1 B1        H2 B2
1      1 0.8333333  6 4.0000000  3
2      2 2.6666667  3 0.8823529 17
3      3 0.3333333  9 0.1250000  8

2) Base R Using ix from above:

replace(df, ix, df[ix] / df[ix+1])

giving:

  Survey        H1 B1        H2 B2
1      1 0.8333333  6 4.0000000  3
2      2 2.6666667  3 0.8823529 17
3      3 0.3333333  9 0.1250000  8

Upvotes: 1

Related Questions