Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

r - Create a new column and fill it by values in same groups

Hello everyone I have a dataframe such as :

  Groups Species Events
1      1     A_1      1
2      1     B_1      1
3      1     A_2      2
4      2     C_1      1
5      2     D_1      3
6      2     C_2      1
7      2     E_1      1

and I would like to add a new columns : Newcol where I add into a [ ] all the df$Species in the same df$Groups and df$Events and separated by a coma. Here in the exemple I should get :

           Groups Species Events Newcol
    1      1     A_1      1      [A_1,B_1]
    2      1     B_1      1      [A_1,B_1]
    3      1     A_2      2      [C_2]
    4      2     C_1      1      [C_1,C_2,E_1]
    5      2     D_1      3      [D_1]
    6      2     C_2      1      [C_1,C_2,E_1]
    7      2     E_1      1      [C_1,C_2,E_1]

Here is the data

structure(list(Groups = c(1L, 1L, 1L, 2L, 2L, 2L, 2L), Species = structure(c(1L, 
3L, 2L, 4L, 6L, 5L, 7L), .Label = c("A_1", "A_2", "B_1", "C_1", 
"C_2", "D_1", "E_1"), class = "factor"), Events = c(1L, 1L, 2L, 
1L, 3L, 1L, 1L)), class = "data.frame", row.names = c(NA, -7L
))

Thanks for your help

question from:https://stackoverflow.com/questions/65933163/create-a-new-column-and-fill-it-by-values-in-same-groups

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use sprintf :

library(dplyr)

df %>%
  group_by(Groups, Events) %>%
  mutate(Newcol = sprintf('[%s]', toString(Species)))

#  Groups Species Events Newcol         
#   <int> <fct>    <int> <chr>          
#1      1 A_1          1 [A_1, B_1]     
#2      1 B_1          1 [A_1, B_1]     
#3      1 A_2          2 [A_2]          
#4      2 C_1          1 [C_1, C_2, E_1]
#5      2 D_1          3 [D_1]          
#6      2 C_2          1 [C_1, C_2, E_1]
#7      2 E_1          1 [C_1, C_2, E_1]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...