Can you use sapply on specific columns within dplyr?

library(dplyr)

How can I use sapply on a dataframe within dplyr? I thought I'd just reference the current object at a given line with a . symbol.

#mtcars but with first row equal to mtcars' rownames
mtcars2 <- 
  cbind(data.frame("names"=rownames(mtcars)), mtcars)

#If I want to make columns 2-the end of mtcars numeric, this works:
sapply(mtcars[,2:ncol(mtcars)], as.numeric)

#Does not work in dplyr
mtcars2 %>%
  sapply(.[,2:ncol(.)], as.numeric)

in dplyr the error is :

Error in match.fun(FUN) :
'.[, 2:ncol(.)]' is not a function, character or symbol

mtcars %>%
  select(-1) %>%
  mutate_all(as.numeric)

Thanks - but doesn't this lose column 1 in the process? I just want to do the sapply to all columns of mtcars2 except column1 (or use a mutate_all like you have), but i still need the first column. De-selecting the column in this way loses it right?

With this avoid transform the first column. But dont delete it. The others colums are trnasform into numeric.

But you lose the 1st column:

#mtcars but with first row equal to mtcars' rownames
mtcars2 <- 
  cbind(data.frame("names"=rownames(mtcars)), mtcars)

mtcars3 <- 
  mtcars2 %>%
  select(-1) %>%
  mutate_all(as.numeric)

  head(mtcars3)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

EDIT:
I guess a way I could do it with select(-1) would be:

  mtcars3 <- 
    cbind(
      mtcars2[,1],
      mtcars2 %>% select(-1) %>% mutate_all(as.numeric)
    )
mtcars2 %>%
  mutate(across(.cols = -1,
                .fns = as.numeric))
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.