简体   繁体   English

基于列值的字符串连接

[英]String concatenation based on values of a column

How can I create a new column "desc" based on the value of column "num"? 如何基于列“ num”的值创建新列“ desc”?

Here is my original dataset. 这是我的原始数据集。 a, b, c, d, e, and f are rownames. a,b,c,d,e和f是行名。

在此处输入图片说明

Here is the output I am looking for. 这是我正在寻找的输出。 Notice that "desc" consists of the rownames of column "num". 请注意,“ desc”由“ num”列的行名组成。 The rownames of num 2 are b and d; num 2的行名是b和d; hence desc of num 2 is "Var : b, d." 因此编号2的desc是“ Var:b,d”。 The rownames of num 3 are c, e, f; num 3的行名是c,e,f; hence desc of num 3 is "Var : c, e, f." 因此编号3的desc是“ Var:c,e,f”。

在此处输入图片说明

Here is the code to create the dataset. 这是创建数据集的代码。

df <- data.frame(num=c(1, 2, 3, 4, 3, 3))
rownames(df) <- c("a", "b", "c", "d", "e", "f")

We create a column from row names ( rownames_to_column ), grouped by 'num', create the 'desc' by paste ing the elements of the row names column ('rn') 我们从行名( rownames_to_column )创建一个列,并按'num'分组,然后通过paste行名列('rn')的元素来创建'desc'

library(tidyverse)
df %>% 
  rownames_to_column('rn') %>% 
  group_by(num) %>% 
  transmute(desc = paste0('var: ', toString(rn)))
# A tibble: 6 x 2
# Groups:   num [3]
#    num desc        
#  <dbl> <chr>       
#1     1 var: a      
#2     2 var: b, d   
#3     3 var: c, e, f
#4     2 var: b, d   
#5     3 var: c, e, f
#6     3 var: c, e, f

data 数据

df <- structure(list(num = c(1, 2, 3, 2, 3, 3)), 
   class = "data.frame", row.names = c("a", 
  "b", "c", "d", "e", "f"))
transform(df, desc = ave(row.names(df), df$num, FUN = function(x) toString(x)))
#  num    desc
#a   1       a
#b   2       b
#c   3 c, e, f
#d   4       d
#e   3 c, e, f
#f   3 c, e, f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM