2021-01-06 Datacamp-Intermediate R

Write a for loop that iterates over all the elements of linkedin and prints out every element separately. Do this in two ways: using the loop version 1 and the loop version 2 in the example code above.

primes <- c(2, 3, 5, 7, 11, 13)

# loop version 1
for (p in primes) {
  print(p)
}

# loop version 2
for (i in 1:length(primes)) {
  print(primes[i])
}

Then here is the code for list, notice that the loop mentioned above is for vector, so just []
but here:
Looping over a list is just as easy and convenient as looping over a vector. There are again two different approaches here:


primes_list <- list(2, 3, 5, 7, 11, 13)

# loop version 1
for (p in primes_list) {
  print(p)
}

# loop version 2
for (i in 1:length(primes_list)) {
  print(primes_list[[i]])
}

Notice that you need double square brackets - [[ ]] - to select the list elements in loop version 2.

Then we have a metric
fist we need paste(), here is the basic principle of paste:
a <- "Hello"
b <- 'How'
c <- "are you? "

print(paste(a,b,c))
print(paste(a,b,c, sep = "-"))
print(paste(a,b,c, sep = "", collapse = ""))

[1] "Hello How are you? "
[1] "Hello-How-are you? "
[1] "HelloHoware you? "

# The tic-tac-toe matrix ttt has already been defined for you

# define the double for loop
for (i in 1:nrow(ttt)) {
  for (j in 1:ncol(ttt)) {
    print(paste("On row",i,"and column",j,"the board contains",ttt[i,j]))
  }
}

Note: how to use paste “,”connect i and j rather than directly put them in the sentence: “on the row....”

# The linkedin vector has already been defined for you
linkedin <- c(16, 9, 13, 5, 2, 17, 14)

# Adapt/extend the for loop
for (li in linkedin) {
  if (li > 10&li<=16) {
    print("You're popular!")
  } else {
    print("Be more visible!")
  }
  
  # Add if statement with break
  if(li>16){
    print("This is ridiculous, I'm outta here!")
    break
  }
  
  
  # Add if statement with next
  if(li<5){
    print("This is too embarrassing!" )
    next
  }
  
  print(li)
}

we have to know: break SHOULD BE INCLUDED IN THE {}!!!!!!!!

Then we should write for loop:
use split(),
!!!!remember the sequence!!!!!!! if (condition) must be ended by {}, do not put 2 if sentences in the same {} (that is where I made the mistake)

# Pre-defined variables
rquote <- "r's internals are irrefutably intriguing"
chars <- strsplit(rquote, split = "")[[1]]

# Initialize rcount
rcount <- 0

# Finish the for loop
for (char in chars) {
    if (char=="r"){
        rcount<-rcount+1
        }
        if(char=="u"){
        break
    }
}

# Print out rcount
print(rcount)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容