Home > Software design >  Take inverse of multiple columns in R dataframe at the same time
Take inverse of multiple columns in R dataframe at the same time

Time:07-13

In the following data frame df, I want to take the inverse of columns "l3" to "l5". I could do this column by column like df$l3 <- 1 / df$l3. But how can I do this for multiple columns at the same time? I want a general code.

df <- data.frame(level = rep(c("A","B"), each = 5), l1 = c(1:10), l2 = c(1:10),l3 = c(1:10),l4 = c(1:10),l5 = c(1:10), l6 = c(1:10),l7 = c(1:10),l8 = c(1:10) )

#level l1 l2 l3 l4 l5 l6 l7 l8
#   A   1  1  1  1  1  1  1 10
#..... omitted .....

CodePudding user response:

Arithmetic is vectorized on data frames. So you can do:

## option 1: index by column names
column_index <- paste0("l", 3:5)
df[column_index] <- 1 / df[column_index]

## option 2: index by column numbers, l3 to l5 are in columns 4 to 6
column_index <- 4:6
df[column_index] <- 1 / df[column_index]

Note that 1 / 0 gives Inf, i.e., infinity.

CodePudding user response:

In this case dplyrs mutate(across(.. is very handy:

library(dplyr)

df %>% 
  mutate(across(l3:l5, ~1/.))
level l1 l2        l3        l4        l5 l6 l7 l8
1      A  1  1 1.0000000 1.0000000 1.0000000  1  1  1
2      A  2  2 0.5000000 0.5000000 0.5000000  2  2  2
3      A  3  3 0.3333333 0.3333333 0.3333333  3  3  3
4      A  4  4 0.2500000 0.2500000 0.2500000  4  4  4
5      A  5  5 0.2000000 0.2000000 0.2000000  5  5  5
6      B  6  6 0.1666667 0.1666667 0.1666667  6  6  6
7      B  7  7 0.1428571 0.1428571 0.1428571  7  7  7
8      B  8  8 0.1250000 0.1250000 0.1250000  8  8  8
9      B  9  9 0.1111111 0.1111111 0.1111111  9  9  9
10     B 10 10 0.1000000 0.1000000 0.1000000 10 10 10
  • Related