Christina
Christina

Reputation: 75

Change column name based on row values

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.

Upvotes: 1

Views: 173

Answers (1)

Jaap
Jaap

Reputation: 83275

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)

Upvotes: 1

Related Questions