简体   繁体   English

如何在 R 的列中添加第一个数字

[英]How to add first number in row in a column in R

Lets say we have the following df假设我们有以下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 ( 1 0 + 1 1) = 2 = number 列的和应该是两个 ( 1 0 + 1 1) = 2

A faster option is to get the substring , convert to numeric and get the sum更快的选择是获取substring ,转换为数字并得到sum

with(df, sum(as.numeric(substring(number, 1, 1))))
[1] 2

Or we may use或者我们可以使用

with(df, sum(number %/% 10))
[1] 2

Using tidyverse :使用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)代表 package (v2.0.1) 于 2021 年 11 月 24 日创建

Substitute x here for you column (eg df$v2 ).在这里用x代替你的列(例如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])}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM