Lets say we have the following df
letter number
a 10
b 11
and I wanted to add only the first number in a column. How would you do that
Result
= number column should have a sum of two (10 11) = 2
CodePudding user response:
A faster option is to get the substring
, convert to numeric and get the sum
with(df, sum(as.numeric(substring(number, 1, 1))))
[1] 2
Or we may use
with(df, sum(number %/% 10))
[1] 2
Or as @rg255 mentioned in the comments, if the number of digits can be different (other than the 2 digit mentioned in the example)
with(df, sum(number %/% 10^(nchar(number)-1)))
CodePudding user response:
Substitute x
here for you column (e.g. df$v2
). This creates a list of the digits within each element, then extracts the first and sums them.
sum(sapply(strsplit(as.character(x), ""), function(i){as.numeric(i[1])}))
CodePudding user response:
Using tidyverse
:
library(tidyverse)
set.seed(111)
df <- tibble(letter = letters[1:10], number = sample(1:100, 10))
summarise(df, sum_first = str_sub(number, 1, 1) %>%
as.numeric() %>%
sum() )
#> # A tibble: 1 × 1
#> sum_first
#> <dbl>
#> 1 52
Created on 2021-11-24 by the reprex package (v2.0.1)