why c("name":"name") does not work?

I have colnames which need " " because they have spaces,
however trying to calculate
rowSums(myTibble[ , c("var name1" : "var name11")], na.rm = FALSE)
results in error:
Error in "var name1" : "var name11" : NA/NaN argument

I want to use names, not colnumbers, and tried with " " and quotes on tilde key but to no success. What is wrong?

PS
I found a workaround (rowSums(myTibble[,c(match("var name1", colnames(myTibble)) : match("var name11", colnames(myTibble)))], na.rm = FALSE) but it is not neat / looks ugly :wink:

Hi,

You can only use : when working with dplyr, it will not work with column names in base R.

library(tidyverse)

myData = tibble(
  "col 1" = 1:5,
  "col 2" = runif(5),
  "col 3" = LETTERS[1:5],
  "col 4" = c(T, T, T, F, F)
)


myData %>% select("col 1":"col 3")
#> # A tibble: 5 × 3
#>   `col 1` `col 2` `col 3`
#>     <int>   <dbl> <chr>  
#> 1       1   0.415 A      
#> 2       2   0.775 B      
#> 3       3   0.202 C      
#> 4       4   0.864 D      
#> 5       5   0.789 E

Created on 2023-01-13 by the reprex package (v2.0.1)

Hope this helps,
PJ

This helps, thank you.

P.S. Is there a quick method to calculate row sums across several columns with R pipe operator?
I mean selecting columns with select("col1":"col3") |> mutate(sum = ....).
I am at a loss how to do it (trying with rowSums() )

library(tidyverse)

myData = tibble(
  "col 1" = 1:5,
  "col 2" = runif(5),
  "col 3" = LETTERS[1:5],
  "col 4" = c(T, T, T, F, F)
)


myData %>% rowwise() %>% 
  mutate(mysum=sum(c_across("col 1":"col 2")))
1 Like

Many thanks!

I did not use c_across(), thinking rowwise() will be enough to tell sum() to calculate sums for rows
(I had tried sum() before rowSums() but it did not work properly :wink: ).

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.