Search code examples
rlistcastingtypecasting-operator

Changing the type of Nth colum elements from List


This is what I came on. Supposedly, the list[[ ]] would mean all the data.frames from the list, which it did not work.

list <- as.Date(list[[]][,2])

Not working, tried something as this

list <- lapply(list[,2], as.Date)

Again an error.

So, that being said, and shown, how can explicit in R languages, that I want to apply the function in all the elements of a column, for all the data.frames of the list, in the best way


Solution

  • I don't know how to do want you want with any of the apply functions but a simple loop works

    data1 = data.frame(y = seq(1,10),x=seq(from = 1789,to = 2789,length.out=10))
    data2 = data.frame(y = seq(11,20),x=seq(from = 1789,to = 2789,length.out=10))
    test = list(data1,data2)
    for(i in 1:length(test)){
      test[[i]][,2] = as.Date(test[[i]][,2],origin = "1899-12-30")
    }
    

    In this case I want to convert numeric excel dates in dates in R. I tried modifying your second option to: lapply(test,function(x) as.Date(x[,2],origin = "1899-12-30")) but you would end up only with dates