首页 > 解决方案 > For循环填充R中的一列

问题描述

我有一个零列和零行的数据框,我想for loop填充从 1 到 39 的数字。这些数字应该重复两次,直到 39,例如,我正在寻找的结果将是一个列,其中每个数字重复两次

假设st是我已经设置的数据框。这是我到目前为止所拥有的:

for(i in 1:39) {
  append(st,i) 
  for(i in 1:39) {
    append(st,i)
  }
}

预期结果将采用列结构:

1
1
2
2
3 
3
.
.
.
.
39
39

标签: rdataframe

解决方案


你不需要使用for loop. 而是使用rep()

# How many times you want each number to repeat sequentially
times_repeat <- 2

# Assign the repeated values as a data frame
test_data <-  as.data.frame(rep(1:39, each = times_repeat))

# Change the column name if you want to
names(test_data) <- "Dont_encourage_the_use_of_blanks_in_column_names"

推荐阅读