Home > Software engineering >  Remove character in a specific column using sub comand and the pipe operator approach in R
Remove character in a specific column using sub comand and the pipe operator approach in R

Time:09-05

I would like to use the sub command to remove this X leaving only the numbers.

I would like to use the %>% pipe operator approach, as it avoids creating intermediate data.frames and makes the code much cleaner.

I tried using something like this, but to no avail:

df<-data.frame(x1=c(20,3,2),x2=c(19,4,2), x3=c(20,3,2))%>%
  pivot_longer(cols=x1:x3, names_to = "name1", values_to = "value1")%>%
  sub('X','','name1')

CodePudding user response:

You need dplyr::mutate to apply a function like sub on a column of your data set, creating new columns or replace the existing ones.

library(dplyr)
library(tidyr)

data.frame(x1=c(20,3,2),x2=c(19,4,2), x3=c(20,3,2))%>%
  pivot_longer(cols=x1:x3, names_to = "name1", values_to = "value1") %>%
  mutate(name1 = sub('[^0-9]', '', name1))


# A tibble: 9 × 2
  name1 value1
  <chr>  <dbl>
1 1         20
2 2         19
3 3         20
4 1          3
5 2          4
6 3          3
7 1          2
8 2          2
9 3          2
  • Related