Hello everyone,
I want to create a function that allows me to run the same code using different variables. I have a data set with unique observation by individual, and three variables (i.e. X,Y, and Z).
I want to perform the following analysis.
myFunc = function(dat,var1,var2){
paste(dat$var2) = ifelse(is.na(paste(dat$var1)), NA,(paste(dat$var2)))
print(paste(dat$var2))
}
myFunc(MyDat,X,Y)
It could also be something like
freq = function(dat,var){
table(dat$var)
}
freq(MyDat,X)
Of course, this is an oversimplification of my problem. As you may have noticed, my main goal is to learn how to combined data frame names & variable names within a function to create new variables (e.g. paste(dat$var2)). Once I learn how to do that, I can use a similar principle to run less basic analysis.
I tried paste(MyDat$X) outside the function and it works perfectly. That’s to say, it shows the X variable from the MyDat data frame. I would appreciate if you have show me how to do that. I posted a similar question in the past, but I did not get a proper answer. Maybe I did not do a good job at explaining my situation. Hopefully, this time I’ll get an answer.
Please, see below a simplified version of my data frame as well as some other information that you may need.
| ID | X | Y | Z |
|---|---|---|---|
| 1 | 1 | 0 | NA |
| 2 | 0 | NA | NA |
| 3 | 1 | 0 | NA |
| 4 | 1 | 0 | NA |
| 5 | 1 | 1 | 1 |
| 6 | 1 | 1 | 1 |
| 7 | 1 | 0 | NA |
| 8 | 1 | 0 | NA |
| 9 | 1 | 1 | 1 |
| 10 | 1 | 1 | 1 |
| 11 | 1 | 1 | 1 |
| 12 | 1 | 1 | 1 |
| 13 | 1 | 0 | NA |
| 14 | 1 | 1 | 0 |
| 15 | 1 | 0 | NA |
| 16 | 1 | 0 | NA |
| 17 | 1 | 1 | 1 |
| 18 | 1 | 0 | NA |
| 19 | 1 | 1 | 0 |
Additional relevant information:
OS: Windows 10 (64-bit)
R version: 3.6.2
R studio version: 3.5
Thanks a lot for your support.
A.G.