changing column types across multiple tables and columns in R

562 Views Asked by At

I have several data frames that share the same column names. For example...

dataframe A with column a,b,c
dataframe B with column c,d,e
dataframe C with column a,b,c,d

I want to convert columns named 'b' and 'c' to character(if these columns exist in the table). Can I achieve this without repeating like this

A$b <-as.character(A$b)
A$c <-as.character(A$c) 
B$b <-as.character(B$c)
1

There are 1 best solutions below

2
On
charnames <- c('a','b','c','d','e')

indA <- colnames(A) %in% charnames
A[indA] <- lapply(A[indA], as.character)

indB <- colnames(B) %in% charnames
B[indB] <- lapply(B[indB], as.character)

# ...

This has the safeguard that if no column names match, the frame is unmodified.

If you are asking about automating even further than this, then I recommend organizing your frames away from individual variables, instead as a list-of-data.frames.

Example of this:

lst <- list(indA, indB)
lst <- lapply(lst, function(df) {
  ind <- colnames(df) %in% charnames
  df[ind] <- lapply(df[ind], as.character)
  df
})