Question

How to replace column in a list of data.tables?

Here is approx. data what I have:

data1 <- data.table(V1=c("Mžn","Tue","Wžd","Thř","Fr"),a2012=rnorm(5),a2011=rexp(5,2))
data2 <- data.table(V1=c("Mžn","Tue","Wžd","Thř","Fr"),a2012=rnorm(5),a2011=rexp(5,2),a2010=rbinom(5,2,0.3))
ListData <- list(data1,data2)

Here is what is going on. Basically I need to get rid of the UTF-8 enconding:

list.ch <- lapply(ListData, "[",,"V1")

Here is some NA coming up but it works on original data so never mind:

TranslList <- lapply(list.ch, function(x) try(iconv(x, "UTF-8", "ASCII//TRANSLIT")))

So I would like to replace the corrected enconding with the original ListData above, basically replacing the column V1 with the encoded names.

matList <- lapply(ListData,as.matrix)
testMat <- lapply(lapply(matList, function(x) x[,-c(1)]),data.table)

FrameList <- mapply(cbind, TranslList, testMat)

The problem in this messy and unnecessary operations is that the column name changes from V1 to some i.e. dots[[1L]][[2L]]

Anyway, how to replace column in a list of data.tables?

Was it helpful?

Solution

It seems like you're making life hard for yourself. A simple lapply() will do:

library(data.table)

wday <- c("Mžn","Tue","Wžd","Thř","Fr")
data1 <- data.table(V1 = wday, a2012 = rnorm(5), a2011 = rexp(5,2))
data2 <- data.table(V1 = wday, a2012 = rnorm(5), a2011 = rexp(5,2),
  a2010 = rbinom(5,2,0.3))
data <- list(data1, data2)

translit <- function(x) iconv(x, "UTF-8", "ASCII//TRANSLIT", sub = "byte")

invisible(lapply(data, function(dt) {
  dt[, V1 := translit(V1)]
}))
data

Note that this modifies your original data in place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top