简体   繁体   English

如何使用for循环在R中创建简单表?

[英]How do I create a simple table in R using for loops?

I was asked to create a table with three columns, A, B and C and eight rows. 我被要求创建一个具有三列的表,A,B,C和八行。 Column A must go 1, 1, 1, 1, 2, 2, 2, 2. Column B must alternate 1, 2, 1, 2, 1, 2, 1, 2. And column C must go 1, 1, 2, 2, 1, 1, 2, 2. I am able to produce the A column data fine, but don't know how to get B or C. This is the code I have so far: A列必须变为1,1,1,1,2,2,2,2 B列必须交替为1,2,1,2,2,1,2,1,2并且C列必须变为1,1,2 ,2、1、1、2、2。我能够很好地产生A列数据,但不知道如何获取B或C。这是我到目前为止的代码:

dataSheet <- matrix(nrow = 0, ncol = 3)  
colnames(dataSheet) <- c('A', 'B', 'C')  
A <- 1 
B <- 1 
C <- 1 

for (A in 1:4){
A=1
dataSheet <- rbind(dataSheet, c(A, B, C)) 
}
for (A in 5:8){
A=2
dataSheet <- rbind(dataSheet, c(A, B, C)) 
}

This seems like a good excuse to get familiar with the rep() function as it easily supports this question, but many more complicated questions if you're clever enough: 这似乎是熟悉rep()函数的一个很好的借口,因为它很容易支持此问题,但如果您足够聪明,则可以解决许多更复杂的问题:

dt <- data.frame(A = rep(1:2, each = 4),
                 B = rep(1:2, times = 4),
                 C = rep(1:2, each = 2))
dt
#>   A B C
#> 1 1 1 1
#> 2 1 2 1
#> 3 1 1 2
#> 4 1 2 2
#> 5 2 1 1
#> 6 2 2 1
#> 7 2 1 2
#> 8 2 2 2

Created on 2019-01-26 by the reprex package (v0.2.1) reprex软件包 (v0.2.1)创建于2019-01-26

Simply use R 's vectorization for this task, ie 只需将R的向量化用于此任务,即

A <- c(1, 1, 1, 1, 2, 2, 2, 2)
B <- c(1, 2, 1, 2, 1, 2, 1, 2) # or rep(1:2, 4)
C <- c(1, 1, 2, 2, 1, 1, 2, 2)
cbind(A,B,C)

Maybe something along the lines of the following will be acceptable by your professor. 也许您的教授可以接受以下内容。

for (i in 1:8){
  A <- if(i <= 4) 1 else 2
  B <- if(i %% 2) 1 else 2
  C <- if(any(i %% 4 == c(0, 1, 4, 5))) 1 else 2
  dataSheet <- rbind(dataSheet, c(A, B, C)) 
}

dataSheet
#     A B C
#[1,] 1 1 1
#[2,] 1 2 2
#[3,] 1 1 2
#[4,] 1 2 1
#[5,] 2 1 1
#[6,] 2 2 2
#[7,] 2 1 2
#[8,] 2 2 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM