R
R - datatype, iteration,vector computation, NA - 2020/01/08
jchung56
2020. 1. 8. 12:30
# find out the data type
is.array(x)
is.null()
is.data.frame(x)
is.factor(x)
is.character(x)
is.matrix(x)
class(x) #[1] "data.frame"
str(x)
#'data.frame': 3 obs. of 1 variable:
# $ banana: int 1 2 3
class(c(1,2))
class(matrix(c(1,2)))
#modify data type
x<-c("a","b","c")
as.factor(x)
as.character(as.factor(x))
data.frame(list(x=c(1,2), y=c(3,4)))
#iterator
if(TRUE){
print("TRUE")
print("hello")
}else{
print("FALSE")
print("world")
}
for(i in 2:10){
print(i)
}
i<-1
while (i<=10) {
print(i)
i<-i+1
}
x<-c(1,2,3,4,5)
ifelse(x %%2==0 ,"even", "odd")
repeat{
print(i)
if(i>=10){
break
}
i<-i+1
}
n= 5
m=2
n%/%m #
n%%m #reminder of n/m
n^m # 5^2
exp(n) # e^n
log(2,base = 2)
log2(2)
1:5 *2 +1
#vector computation
x<-c(1,2,3,4,5,6)
x+1
#for vector computation, we use & (not &&)
x+x
x==x
c(T,T,T)& c(T,F,T)
sum(x)
median(x)
mean(x)
#NA
NA & TRUE #NA
NA+1 #NA
sum(c(1,2,3,NA))#NA
sum(c(1,2,3,NA), na.rm = TRUE) #6
x<-data.frame(a=c(1,2,3),b=c("a","b",NA),c=c("a",NA,"c"))
na.fail(x) #if object has NA, then execution fails
na.omit(x) #if object has NA, then omit NA
na.exclude(x)#if object has NA, then execute excluding NA, (function using naresid, napredict, result include na
na.pass(x) #regardless of existence of NA, execute x
df<-data.frame(x=1:5,y=seq(2,10,2))
df[3,2]=NA
df
#y=ax+b linear model
#Resid() : linear model, find out residual (difference of expected value and true value of y)
resid(lm(y~x, data = df, na.action = na.omit))
resid(lm(y~x, data = df, na.action = na.exclude))