MYaseen208
MYaseen208

Reputation: 23898

Divide a row of numeric variables by a constant

I want to divide first row of all numeric columns by 3.

City <- rep(LETTERS[1:3], each = 2) 
Res  <- factor(rep(c("Urban", "Rural"), times = length(City)/2))
set.seed(12345)
Pop  <- rpois(n = length(City), lambda = 500000)
Pop1 <- rpois(n = length(City), lambda = 500)
df   <- data.frame(City, Res, Pop, Pop1)
df

df[1, 3:4]/3
       Pop     Pop1
1 166804.7 164.3333

Wonder how this can be accomplished with tidyverse.

Upvotes: 1

Views: 354

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269556

If you want just the third and fourth columns of the first row divided by 3:

df %>% slice(1) %>% select(3:4) %>% mutate_all(~ . / 3)
##        Pop     Pop1
## 1 166804.7 164.3333

or if you wanted all the columns of the first row with just third and fourth columns divided by 3:

df %>% slice(1) %>% mutate_at(3:4, ~ . / 3)
##   City   Res      Pop     Pop1
## 1    A Urban 166804.7 164.3333

Upvotes: 1

akrun
akrun

Reputation: 887108

An option would be

library(tidyverse)
df %>% 
  mutate_if(is.numeric, list(~ case_when(row_number()==1 ~ ./3, 
            TRUE ~ as.numeric(.))))

If we need to return only a single row with selected variables

df %>%
    slice(1) %>%
    select_if(is.numeric) %>%
    mutate_all(list(~ ./3))

Upvotes: 1

Related Questions