I am trying to compute a few new variables in my framework. Take the initial values, for example:
Let's say I have:
Dataset <- data.frame(time=rep(c(1990:1992),2), geo=c(rep("AT",3),rep("DE",3)),var1=c(1:6), var2=c(7:12)) time geo var1 var2 1 1990 AT 1 7 2 1991 AT 2 8 3 1992 AT 3 9 4 1990 DE 4 10 5 1991 DE 5 11 6 1992 DE 6 12
I want too:
time geo var1 var2 var1_1990 var1_1991 var2_1990 var2_1991 1 1990 AT 1 7 1 2 7 8 2 1991 AT 2 8 1 2 7 8 3 1992 AT 3 9 1 2 7 8 4 1990 DE 4 10 4 5 10 11 5 1991 DE 5 11 4 5 10 11 6 1992 DE 6 12 4 5 10 11
Thus, time and variable are changed for new variables. Here is my attempt:
intitialyears <- c(1990,1991) intitialvars <- c("var1", "var2")
The work is done without errors, but does not give anything. I would like to name the variables in the example (for example, "var1_1990") and immediately make the new variables part of the data frame. I would also like to avoid the for loop, but I don't know how to wrap two applications around this function. Should I use a function to use two arguments? The problem is that the apply function does not carry the results in my environment? I have been stuck here for a while, so I will be grateful for any help!
ps: I have a solution to make this combination a combination without use and the like, but I'm trying to get away from copying and pasting:
Dataset$var1_1990 <- c(rep(Dataset$var1[which(Dataset$time==1990)], each=length(unique(Dataset$time))))
r dataframe lapply
Peter Pan
source share