I think purrr::map
or lapply
offer fairly elegant solutions here (and just say no to for-loops in R if possible):
Let's make you a fake data frame with all character vectors:
> df <- data.frame(let1 = c('a', 'b', 'c'), num1 = c('1', '2', '3'),
let2 = c('d', 'e', 'f'), num2 = c('4', '5', '6'),
num3 = c('7', '8', '9'), let3 = c('g', 'h', 'i'),
stringsAsFactors = FALSE)
> str(df)
'data.frame': 3 obs. of 6 variables:
$ let1: chr "a" "b" "c"
$ num1: chr "1" "2" "3"
$ let2: chr "d" "e" "f"
$ num2: chr "4" "5" "6"
$ num3: chr "7" "8" "9"
$ let3: chr "g" "h" "i"
Then we want to change num1
, num2
, and num3
into integer vectors (columns 2, 4, and 5). For illustration, copy df
to df2
and then use purrr::map
. Here I refer to the columns by their column number, but you could also use the names.
> df2 <- df
> df2[, c(2,4,5)] <- purrr::map(df2[, c(2,4,5)], as.integer)
> str(df2)
'data.frame': 3 obs. of 6 variables:
$ let1: chr "a" "b" "c"
$ num1: int 1 2 3
$ let2: chr "d" "e" "f"
$ num2: int 4 5 6
$ num3: int 7 8 9
$ let3: chr "g" "h" "i"
If you don't want to load any other packages, lapply
will work:
> df3 <- df
> df3[, c(2,4,5)] <- lapply(df3[, c(2,4,5)], as.integer)
> str(df3)
'data.frame': 3 obs. of 6 variables:
$ let1: chr "a" "b" "c"
$ num1: int 1 2 3
$ let2: chr "d" "e" "f"
$ num2: int 4 5 6
$ num3: int 7 8 9
$ let3: chr "g" "h" "i"