hmje
hmje

Reputation: 117

How can I use mutate() with a string column?

I have a tibble something like

data <- tibble(string = c("A", "B", "C"), number = c(1,2,3))

Then I defined a function

foo <- function(string, number){
  result <- paste(replicate(number, string), collapse = "")
  return(result)
}

so that foo("A", 3) = "AAA". Now what I want to do is to add a new column new where the value for each row is foo(s, n), given that s and n are the values of string and number for the same row. I tried to do this by doing something like

mutate(data, new = foo(string, number))

but I failed and don't know why.

Upvotes: 0

Views: 1525

Answers (2)

AnilGoyal
AnilGoyal

Reputation: 26218

In this scenario, there is no need to define a new function. This will work-

data %>% mutate(new = strrep(string, number))

# A tibble: 3 x 3
  string number new  
  <chr>   <dbl> <chr>
1 A           1 A    
2 B           2 BB   
3 C           3 CCC 

Upvotes: 0

tamtam
tamtam

Reputation: 3671

Try rowwise, therefore foo is calculated for each row.

data %>%
  rowwise() %>%
  mutate(new = foo(string, number))

Output:

# A tibble: 3 x 3
# Rowwise: 
  string number new  
  <chr>   <dbl> <chr>
1 A           1 A    
2 B           2 BB   
3 C           3 CCC 

The problem might be that foo cant handle vectors. Like in this examples. So a rowwise apprach is needed.

foo(c("A", "B"), c(1,2))
# Error in integer(n) : invalid 'length' argument 

foo(data$string, data$number)
# Error in integer(n) : invalid 'length' argument 

Upvotes: 1

Related Questions