For the data tables below, I would like to rename the column fruit if it contains either "apple" or "orange", i.e. I'd like to rename the column fruit within DT but not within DT2.
library(data.table)
DT <- data.table(colour = c("green", "red", "red", "red", "blue","red"), fruit = c("apple", "orange", "pear", "apple", "apple","banana"))
DT2 <- data.table(colour = c("green", "red", "red", "red", "blue","red"), fruit = c("pear", "pear", "pear", "banana", "pear","banana"))
I want to first search for whether the data table contains the column fruit, so I tried the code below but it renames fruit within DT and within DT2:
alist <- list(DT, DT2)
lapply(alist, function(x) {
if ("fruit" %in% colnames(x)){
x <- x[fruit=="apple"|fruit=="orange", setnames(x, old="fruit", new="appfruit")]
x}})
Any help would be greatly appreciated.
if (any(grepl("apple|orange", DT$fruit))) colnames(DT)[2] <- "appfruit"