根据分组属性添加新列

时间:2018-07-04 02:20:25

标签: r

我想在R中添加一个新列,以将我的子组汇总为组。

这是我的示例:

id = c(1,2,2,3,4,4,4,5,5,5,6,6,6)
subgroup = c("lightred","lightblue","darkblue","lightred","darkred","darkred","lightblue","darkgreen","darkgreen","lightgreen","darkred","darkblue","lightgreen")
data = data.frame(cbind(id,subgroup))

> data
   id   subgroup
1   1   lightred
2   2  lightblue
3   2   darkblue
4   3   lightred
5   4    darkred
6   4    darkred
7   4  lightblue
8   5  darkgreen
9   5  darkgreen
10  5 lightgreen
11  6    darkred
12  6   darkblue
13  6 lightgreen

现在,我想添加一个新列“颜色”,将属性分为3个格点“红色”,“绿色”和“蓝色”,而不论它们是浅色还是深色。

最后应该是这样的:

   id   subgroup colour
1   1   lightred    red
2   2  lightblue   blue
3   2   darkblue   blue
4   3   lightred    red
5   4    darkred    red
6   4    darkred    red
7   4  lightblue   blue
8   5  darkgreen  green
9   5  darkgreen  green
10  5 lightgreen  green
11  6    darkred    red
12  6   darkblue   blue
13  6 lightgreen  green

3 个答案:

答案 0 :(得分:2)

我认为sub在这里应该可行:

data$colour <- sub("^(?:light|dark)", "", data$subgroup)

Demo

答案 1 :(得分:0)

尽管这种方法不像其他方法那么巧妙,但它却非常灵活。我对ops的样本数据进行了调整,以显示如何组合不遵循明/暗范式的多个组。

编辑:

已更新帖子,以在评论中回答操作者的问题。

id = c(1,2,2,3,4,4,4,5,5,5,6,6,6)
subgroup = c("lightred","lightblue","cyan","lightred","water","darkred","lightblue","darkgreen","darkgreen","lightgreen","darkred","darkblue","lightgreen")
data = data.frame(cbind(id,subgroup))


library(dplyr)
data <- data %>% 
  dplyr::mutate(
    colour = dplyr::case_when(
      grepl("red"  , subgroup, fixed = TRUE) ~ "red",
      grepl("(blue)|(cyan)|(water)", subgroup, perl = TRUE) ~ "blue",
      grepl("green", subgroup, fixed = TRUE) ~ "green",
      TRUE ~ "else"
    )
  )
data

答案 2 :(得分:0)

来自stringr

stringr::str_extract(data$subgroup,"red|green|blue")
 [1] "red"   "blue"  "blue"  "red"   "red"   "red"   "blue"  "green" "green" "green" "red"   "blue"  "green"



data$color=stringr::str_extract(data$subgroup,"red|green|blue")
data
   id   subgroup color
1   1   lightred   red
2   2  lightblue  blue
3   2   darkblue  blue
4   3   lightred   red
5   4    darkred   red
6   4    darkred   red
7   4  lightblue  blue
8   5  darkgreen green
9   5  darkgreen green
10  5 lightgreen green
11  6    darkred   red
12  6   darkblue  blue
13  6 lightgreen green