0

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)
phiver
  • 19,366
  • 14
  • 36
  • 42
hyoo88
  • 1

1 Answers1

0
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
})
r2evans
  • 77,184
  • 4
  • 55
  • 96
  • Thanks! This is very helpful and yes I am looking to automating it further so I don't have to copy and paste above scripts. I defined a list of my data frames and used it as a variable in a loop function.. It did not quite work for me..Could you provide a bit more guide on how to do that? thanks again! – hyoo88 May 08 '18 at 22:00
  • See my edit, hope it helps. – r2evans May 09 '18 at 03:37