减去特定行并重命名它
subtract specific row und rename it
是否可以减去某些行并重命名它们?
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)
结果应该是这样的:
year
category
value
2005
a
2
2005
b
2
2005
c
4
2006
a
3
2006
b
3
2006
c
12
2007
a
4
2007
b
4
2007
c
16
2005
c-b
2
2006
c-b
9
2007
c-b
12
您可以使用 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
参见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")
是否可以减去某些行并重命名它们?
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)
结果应该是这样的:
year | category | value |
---|---|---|
2005 | a | 2 |
2005 | b | 2 |
2005 | c | 4 |
2006 | a | 3 |
2006 | b | 3 |
2006 | c | 12 |
2007 | a | 4 |
2007 | b | 4 |
2007 | c | 16 |
2005 | c-b | 2 |
2006 | c-b | 9 |
2007 | c-b | 12 |
您可以使用 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
参见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")