减去特定行并重命名它

发布于 2025-01-09 20:55:58 字数 1156 浏览 3 评论 0原文

是否可以减去某些行并重命名它们?

year <- c(2005,2005,2005,2006,2006,2006,2007,2007,2007)
category <- c("a","b","c","a","b","c", "a", "b", "c")
value <- c(2,2,10,3,3,12,4,4,16)
df <- data.frame(year, category,value, stringsAsFactors = FALSE)

结果应如下所示:

类别
2005a2
2005b2
2005c4
2006a3
2006b3
2006c12
2007a4
2007b4
2007c16
2005CB2
2006CB9
2007CB12

it is possible to subtract certain rows and rename them?

year <- c(2005,2005,2005,2006,2006,2006,2007,2007,2007)
category <- c("a","b","c","a","b","c", "a", "b", "c")
value <- c(2,2,10,3,3,12,4,4,16)
df <- data.frame(year, category,value, stringsAsFactors = FALSE)

And this is how the result should look:

yearcategoryvalue
2005a2
2005b2
2005c4
2006a3
2006b3
2006c12
2007a4
2007b4
2007c16
2005c-b2
2006c-b9
2007c-b12

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疏忽 2025-01-16 20:55:58

您可以使用group_modify

library(tidyverse)
df %>% 
  group_by(year) %>% 
  group_modify(~ add_row(.x, category = "c-b", value = .x$value[.x$category == "c"] - .x$value[.x$category == "b"]))

# A tibble: 12 x 3
# Groups:   year [3]
    year category value
   <dbl> <chr>    <dbl>
 1  2005 a            2
 2  2005 b            2
 3  2005 c           10
 4  2005 c-b          8
 5  2006 a            3
 6  2006 b            3
 7  2006 c           12
 8  2006 c-b          9
 9  2007 a            4
10  2007 b            4
11  2007 c           16
12  2007 c-b         12

You can use group_modify:

library(tidyverse)
df %>% 
  group_by(year) %>% 
  group_modify(~ add_row(.x, category = "c-b", value = .x$value[.x$category == "c"] - .x$value[.x$category == "b"]))

# A tibble: 12 x 3
# Groups:   year [3]
    year category value
   <dbl> <chr>    <dbl>
 1  2005 a            2
 2  2005 b            2
 3  2005 c           10
 4  2005 c-b          8
 5  2006 a            3
 6  2006 b            3
 7  2006 c           12
 8  2006 c-b          9
 9  2007 a            4
10  2007 b            4
11  2007 c           16
12  2007 c-b         12
娇俏 2025-01-16 20:55:58

请参阅 substract() 函数。

示例:

substracted_df<-substr(df,df$category=="c")

如果您想知道正在处理哪些行,请使用 which()

rows<-which(df$category=="c")
substracted_df<-df[rows, ]

您可以将每个所需行重命名为

row.names(substracted_df)<-c("Your desired row names")

See substract() function.

Example:

substracted_df<-substr(df,df$category=="c")

If you want to know which rows are you dealing with, use which()

rows<-which(df$category=="c")
substracted_df<-df[rows, ]

You can rename each desired row as

row.names(substracted_df)<-c("Your desired row names")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文