R高级数据管理--重复和循环、条件执行、转置

#R高级数据管理--重复和循环、条件执行、转置

#1.重复和循环
for (i in 1:5) print("hello")    #循环5次 
# [1] "hello"
# [1] "hello"
# [1] "hello"
# [1] "hello"
# [1] "hello"


x <- 5
while(x>0) {print("hi");x <- x-1}    
# [1] "hi"
# [1] "hi"
# [1] "hi"
# [1] "hi"
# [1] "hi"



#2.条件执行

#if else
x <- 1
if (x!=1) print("F") else print("M")
# [1] "M"


#ifelse
ifelse(x>1,print("M"),print("F"))
# [1] "F"
# [1] "F"


#switch

feeling <- c("sad","afraid")
for (i in feeling)
  print(switch(i,happly="I am glad",afraid="I will accompany",sad="cheer up"))
# [1] "cheer up"
# [1] "I will accompany"


#3.转置
head(mtcars)
cars <-mtcars[1:5,1:4]
cars
# mpg cyl disp  hp
# Mazda RX4         21.0   6  160 110
# Mazda RX4 Wag     21.0   6  160 110
# Datsun 710        22.8   4  108  93
# Hornet 4 Drive    21.4   6  258 110
# Hornet Sportabout 18.7   8  360 175

t(cars)  #行列转置
# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
# mpg         21            21       22.8           21.4              18.7
# cyl          6             6        4.0            6.0               8.0
# disp       160           160      108.0          258.0             360.0
# hp         110           110       93.0          110.0             175.0

你可能感兴趣的:(R高级数据管理--重复和循环、条件执行、转置)