我想创建一个新的列列的行合计的基础上列范围内给出的文本列(col_range).我try 了以下操作,它抛出了一个错误.有人知道怎么做吗.

d = data.frame(index_id = c("a1232","c198", "s345","2ert", "e234","e567"),
               yr_ref = c(2023,2024,2025,2024,2027,NA),
               temp2023 = c(2000,5000,2300,2000,1000,200),
               temp2024 = c(3000,3000,3000,0,0,200),
               temp2025 = c(2000,3000,0,800,8000,200),
               temp2026 = c(300,200,1000,0,0,200),
               temp2027= c(1300,1200,100,10,10,200),
               col_range = c("temp2023:temp2023","temp2023:temp2024","temp2023:temp2025","temp2023:temp2024","temp2023:temp2027",NA))

d= d %>% 
  mutate(temp_total= ifelse(!is.na(yr_ref),
                               sum(c_across(col_range)),NA))

#### ERROR
Error in `mutate()`:
ℹ In argument: `temp_total = ifelse(!is.na(yr_ref), sum(c_across(col_range)), NA)`.
Caused by error in `sum()`:
! invalid 'type' (character) of argument
Run `rlang::last_trace()` to see where the error occurred.```

推荐答案

灵感来自@Isaac

library(tidyverse)
    
d %>% 
  rowwise() %>% 
  mutate(total = ifelse(!is.na(yr_ref), 
                        map_dbl(col_range, ~ rowSums(across(str_split_1(.x, pattern = ":")[1]:str_split_1(.x, pattern = ":")[2]))), NA))  

# A tibble: 6 x 9
# Rowwise: 
  index_id yr_ref temp2023 temp2024 temp2025 temp2026 temp2027 col_range         total
  <chr>     <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl> <chr>             <dbl>
1 a1232      2023     2000     3000     2000      300     1300 temp2023:temp2023  2000
2 c198       2024     5000     3000     3000      200     1200 temp2023:temp2024  8000
3 s345       2025     2300     3000        0     1000      100 temp2023:temp2025  5300
4 2ert       2024     2000        0      800        0       10 temp2023:temp2024  2000
5 e234       2027     1000        0     8000        0       10 temp2023:temp2027  9010
6 e567         NA      200      200      200      200      200 NA                   NA

R相关问答推荐

过滤矩阵以获得R中的唯一组合

R:更新后无法运行控制台

如何在RMarkdown LaTex PDF输出中包含英语和阿拉伯语?

将非重复序列高效转换为长格式

如果某些列全部为NA,则更改列

如何删除最后一个可操作对象

解析R函数中的变量时出现的问题

如何基于两个条件从一列中提取行

使用Scale_*_MANUAL时在图例中保留未使用的系数级别

在R中,我如何使用滑动窗口计算位置,然后进行过滤?

如何在PDF格式的kableExtra表格中显示管道字符?

来自程序包AFEX和amp;的类/函数和NICE_TABLE&冲突

将多个变量组合成宽格式

如何对r中包含特定(未知)文本的行求和?

为什么这个表格格罗布不打印?

我需要使用ggplot2制作堆叠条形图

如何使用ggplot2根据绘图中生成的斜率对小平面进行排序?

在直方图中显示两个变量

从单个html段落中提取键-值对

在分面的ggplot2条形图中对条形图进行排序,并省略每组未使用的系数级别