###QUESTION 09

###Topic: Sheet 8 Exercise 2
###Question: I feel I struggle a little to differentiate what R is already capable of doing,
#therefore I end up complicating more the command.
#So my question here would be: the for loop, would not be necessary in vectors then?
#If so, then would it only be necessary on data frames? or also in lists and matrices? ( for function creating)

testdata <- (c(1, 2, NA, 7, NA, 6))

#My version:
which.NNA<- function(data) {
for (i in 1:length(data)){
NNA<- which(is.na(c(data)))
fNNA<- data[-NNA]
}
return(fNNA)
}
which.NNA(testdata)
## [1] 1 2 7 6
#Solution:
mynna<- function(data){
return(data[!is.na(data)])
}
mynna(testdata)
## [1] 1 2 7 6
###Answer:
#For the vector, the for loop would not be necessary, to save computational power you should actually avoid it
#You could actually use the command in the solution for any type of data
testdata.frame <- as.data.frame(testdata)
mynna(testdata.frame)
## [1] 1 2 7 6
testdata.list <- as.list(testdata)
mynna(testdata.list)
## [[1]]
## [1] 1
##
## [[2]]
## [1] 2
##
## [[3]]
## [1] 7
##
## [[4]]
## [1] 6
testdata.matrix <- as.matrix(testdata)
mynna(testdata.matrix)
## [1] 1 2 7 6
#For two-dimensional datasets the code without loop also works, but it will not return a data frame
testdata.frame2
##      V1     V2
## 1   age gender
## 2     3      M
## 3     1      F
## 4   0.5      M
## 5     5      F
## 6     2      F
## 7  <NA>   <NA>
## 8   0.5   <NA>
## 9     5   <NA>
## 10 <NA>      F
## 11 <NA>      F
## 12    7      M
## 13    7      M
## 14    1   <NA>
## 15  0.5      F
## 16    1      M
## 17    5      F
## 18 <NA>      F
## 19    8      M
## 20  0.5      M
## 21    6      F
mynna(testdata.frame2)
##  [1] "age"    "3"      "1"      "0.5"    "5"      "2"      "0.5"    "5"
##  [9] "7"      "7"      "1"      "0.5"    "1"      "5"      "8"      "0.5"
## [17] "6"      "gender" "M"      "F"      "M"      "F"      "F"      "F"
## [25] "F"      "M"      "M"      "F"      "M"      "F"      "F"      "M"
## [33] "M"      "F"
#Same for two-dimensional matrices
testdata.matrix2 <- matrix(c(1, 2, NA, 7, NA, 6),5, 6)
testdata.matrix2
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    6   NA    7   NA    2
## [2,]    2    1    6   NA    7   NA
## [3,]   NA    2    1    6   NA    7
## [4,]    7   NA    2    1    6   NA
## [5,]   NA    7   NA    2    1    6
mynna(testdata.matrix2)
##  [1] 1 2 7 6 1 2 7 6 1 2 7 6 1 2 7 6 1 2 7 6