1

Let's say I have this data frame in R:

df<-data.frame(Id=1:4,name=c("a_b[b]","c_c[f]","g_h[a]","m_a[c]"))
> df
  Id   name
1  1 a_b[a]
2  2 c_c[a]
3  3 g_h[a]
4  4 m_a[a]

I want to remove brackets and everything inside it and get this data frame as output:

Id   name new_name
1  1 a_b[a]      a_b
2  2 c_c[a]      c_c
3  3 g_h[a]      g_h
4  4 m_a[a]      m_a

I have a large data frame with these brackets but whenever I tried functions from tidyr or stringr libraries, it didn't work well because of those brackets. It might be simple but I couldn't do it. Thanks

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Amir Kooi
  • 19
  • 3

1 Answers1

0

You can do that with sub and a regular expression.

sub("\\[.*\\]", "", df$name)
[1] "a_b" "c_c" "g_h" "m_a"
df$new_name = sub("\\[.*\\]", "", df$name)
df
  Id   name new_name
1  1 a_b[b]      a_b
2  2 c_c[f]      c_c
3  3 g_h[a]      g_h
4  4 m_a[c]      m_a
G5W
  • 36,531
  • 10
  • 47
  • 80