简体   繁体   中英

Converting columns from character to integer, but only if the tittle of the column/variable name includes the word "Average"

Basically what the title says! I have columns like name, age, year, average_points, average_steals, average_rebounds etc. But all the average columns (there are a lot) are stored as characters. Thanks!

First I created some random data. You can mutate across the columns that starts_with "average" and convert them to as.integer . You can use the following code:

df <- data.frame(name = c("A", "B"),
                 age = c(10, 51),
                 year = c(2001, 1980),
                 average_points = c("3", "5"),
                 average_steals = c("4","6"),
                 average_bounds = c("6","7"))

str(df)
#> 'data.frame':    2 obs. of  6 variables:
#>  $ name          : chr  "A" "B"
#>  $ age           : num  10 51
#>  $ year          : num  2001 1980
#>  $ average_points: chr  "3" "5"
#>  $ average_steals: chr  "4" "6"
#>  $ average_bounds: chr  "6" "7"
library(dplyr)
library(tidyr)
result <- df %>% 
  mutate(across(starts_with("average"), as.integer))
str(result)
#> 'data.frame':    2 obs. of  6 variables:
#>  $ name          : chr  "A" "B"
#>  $ age           : num  10 51
#>  $ year          : num  2001 1980
#>  $ average_points: int  3 5
#>  $ average_steals: int  4 6
#>  $ average_bounds: int  6 7

Created on 2022-07-20 by the reprex package (v2.0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM