0

I am new in using apply and functions together and I am stuck and frustrated. I have 2 different list of data frames that I need to add certain number of columns to the first one when a condition is fulfill related to the second one. Below this is the structure of the first list that has one data frame for any station and every df has 2 or more columns with each pressure:

> str(KDzlambdaEG)
List of 3
$ 176:'data.frame':    301 obs. of  3 variables:
..$ 0 : num [1:301] 0.186 0.182 0.18 0.181 0.177 ...
..$ 5 : num [1:301] 0.127 0.127 0.127 0.127 0.127 ...
..$ 20: num [1:301] 0.245 0.241 0.239 0.236 0.236 ...
$ 177:'data.frame':    301 obs. of  2 variables:
..$ 0 : num [1:301] 0.132 0.132 0.132 0.13 0.13 ...
..$ 25: num [1:301] 0.09 0.092 0.0902 0.0896 0.0896 ...
$ 199:'data.frame':    301 obs. of  2 variables:
..$ 0 : num [1:301] 0.181 0.182 0.181 0.182 0.179 ...
..$ 10: num [1:301] 0.186 0.186 0.185 0.183 0.184 ...

On the other hand I have the second list that have the number of columns that I need to add after every column on each data frame of the first list :

> str(dif)
List of 3
[[176]]
[1]  4 15 28
[[177]]
[1] 24 67
[[199]]
[1]  9 53

I´ve tried tonnes of things even this, using the append_col function that appear in: How to add a new column between other dataframe columns?

for (i in 1:length(dif)){
A<-lapply(KDzlambdaEG,append_col,rep(list(NA),dif[[i]][1]),after=1)
}

but nothing seems to work so far... I have searched for answers here but its difficult to find specific ones being a newcomer.

Community
  • 1
  • 1

1 Answers1

0

Try:

indxlst <- lapply(dif, function(x) c(1, x[-length(x)]+1, x[length(x)]))
newdflist <- lapply(indxlst, function(x) data.frame(matrix(0, 2, sum(x))))
for(i in 1:length(newdflist)) {
  newdflist[[i]][indxlst[[i]]] <- KDzlambdaEG[[i]]
}

Reproducible Data Test

df1 <- data.frame(x=1:2, y=c("Jan", "Feb"), z=c("A", "B"))
df3 <- df2 <- df1[,-3]
KDzlambdaEG <- list(df1,df2,df3)

x1 <- c(4,15,28)
x2 <- c(24,67)
x3 <- c(9, 53)
dif <- list(x1,x2,x3)

indxlst <- lapply(dif, function(x) c(1, x[-length(x)]+1, x[length(x)]))
newdflist <- lapply(indxlst, function(x) data.frame(matrix(0, 2, sum(x))))
for(i in 1:length(newdflist)) {
  newdflist[[i]][indxlst[[i]]] <- KDzlambdaEG[[i]]
}
newdflist
Pierre L
  • 28,203
  • 6
  • 47
  • 69
  • Thank you so much for taking the time to help me! Kinda work but not the way I expected to be...The numbers of new columns added wasn´t were i wanted and also were added in the wrong position. i will post an output to show you – Carla Berghoff Jul 16 '15 at 19:11
  • Well due to the choice of counting zero as a column, just subtract one from the first element of the `dif` list. Something like this `dif2 <- lapply(dif, function(x) c(x[1]-1, x[-1]))`, then do the operation again. – Pierre L Jul 16 '15 at 20:01