1

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.

1
  • if (any(grepl("apple|orange", DT$fruit))) colnames(DT)[2] <- "appfruit" Commented Nov 28, 2018 at 11:52

1 Answer 1

1

Changing your function to:

lapply(alist, function(x) {
  if(any(x[["fruit"]] %in% c("apple","orange"))) {
    setnames(x, old = "fruit", new = "appfruit")
  }}
)

will give the intended result (see below for extended example data):

> alist
[[1]]
   colour appfruit
1:  green    apple
2:    red   orange
3:    red     pear
4:    red    apple
5:   blue    apple
6:    red   banana

[[2]]
   colour  fruit
1:  green   pear
2:    red   pear
3:    red   pear
4:    red banana
5:   blue   pear
6:    red banana

[[3]]
   colour veggie
1:  green  apple
2:    red   pear
3:    red   pear
4:    red banana
5:   blue   pear
6:    red banana

As you can see, when there is no fruit-column, the columnname is not changed.


Used data:

DT1 <- 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"))
DT3 <- data.table(colour = c("green", "red", "red", "red", "blue","red"), veggie = c("apple", "pear", "pear", "banana", "pear","banana"))

alist <- list(DT1, DT2, DT3)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.