1

How can I create a new column "desc" based on the value of column "num"?

Here is my original dataset. a, b, c, d, e, and f are rownames.

enter image description here

Here is the output I am looking for. Notice that "desc" consists of the rownames of column "num". The rownames of num 2 are b and d; hence desc of num 2 is "Var : b, d." The rownames of num 3 are c, e, f; hence desc of num 3 is "Var : c, e, f."

enter image description here

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")

2 Answers 2

3

We create a column from row names (rownames_to_column), grouped by 'num', create the 'desc' by pasteing the elements of the row names column ('rn')

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"))
Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.