Home > Back-end >  r change column type of columns names with pattern
r change column type of columns names with pattern

Time:10-13

If my dataset has columns like this

ID   Group  Col_item_01   Col_item_02   Col_item 03  
1    Blue    11.23        10.12         4.3
2    Green   10.21        18.24         5.9
4    Purple  4.23          7.64         15.97

How can I convert all the columns starting with , Col_item_... to type numeric from character ? I know I can do this individually , df1$Col_item_01 <- as.numeric(as.character(df1$Col_item_01) but I am interested in an efficient approach using grep or grepl or string functions to extract just these columns starting with Col_item_... and changing them to numeric. Any suggestion is much appreciated. Thanks.

CodePudding user response:

We may loop across the columns that starts_with 'Col_item_' and convert to numeric in tidyverse

library(dplyr)
df1 <- df1 %>%
       mutate(across(starts_with("Col_item_"),
              ~ as.numeric(as.character(.))))

Or in base R, get the column names with pattern using grep and loop over the selected columns in lapply and do the assignment

nm1 <- grep("^Col_item_", names(df1))
df1[nm1] <- lapply(df1[nm1], function(x) as.numeric(as.character(x)))

CodePudding user response:

Use type.convert:

df1 <- type.convert(df1, as.is = TRUE)
  • Related