R语言实战(二)

作者: liu_ll | 来源:发表于2019-02-13 20:17 被阅读11次

问题1:如何寻找一个数列中的偶数呢?

1:seq(2,19,2)
#可以找到2-19中所有的偶数
2:for (i in c(1:10)) if (i%%2 == 0) print(i)

问题2:如何实现比大小和替换? ####把大于3的替换成0,如果有NA怎么办呢?

1:z <- c(1,2,3,4,5,6,7)
a <- length(z)
b <- c()
for  (i in 1:a) {
    if (z[i]>3) z[i]<-0 
  }
z
2:z <-c(1,3,5,6,11)
z[z>5] <-0

3:z <- c(1,NA,NA,NA,4,5,6,83,2)
subset(z,z>3)

问题3:如何知道这些数字所在的位置呢?
用which函数,(ps:如果是想知道第一个的位置呢?)

1:z <- c(1,NA,NA,NA,4,5,6,83,2)
which(z>3)
2:first1 <- function(x){
  for (i in 1:length(x)) {
    if (x[i] == 1 ) break
  }
  return(i)
}

问题4:ifelse的使用
ifelse(b,u,v) #如果b成立,则u,否则v

x <- 1:10
y <- ifelse(x%%2 ==0,5,12)
> y
 [1] 12  5 12  5 12  5 12  5 12  5

问题5:ifelse嵌套会如何?

> g<- c("M","F","F","I","M","M","F","I")
> g
[1] "M" "F" "F" "I" "M" "M" "F" "I"
> ifelse(g =="M",1,ifelse(g=="F",2,3))
[1] 1 2 2 3 1 1 2 3

问题6:如果是要形成一个列表如何形成?
还是上述的那个例子 g<- c("M","F","F","I","M","M","F","I")

grps <- list()
> for (i in c("M","F","I")) grps[[i]] <- which(g==i)
> greps
$M
[1] 1 5 6

$F
[1] 2 3 7

$I
[1] 4 8

相关文章

网友评论

    本文标题:R语言实战(二)

    本文链接:https://www.haomeiwen.com/subject/gdodeqtx.html