我正在寻找有关如何在数据框中添加一列的建议,该列对于每个因子级别从1到n均属于该级别的因子数。这是我正在使用的示例。
collatzRule <- function(m){
if ( m %% 2 == 0) {
return(m/2)
} else {
return(3*m + 1)
}
}
collatz <- function(n, limit = 1000000000) {
# collatz numbers will go in this vector
numbers <- numeric(limit)
# keep count of how many numbers we have made:
counter <- 0
while ( n > 1 & counter < limit) {
# need to make a new number
counter <- counter + 1
# put the current number into the vector
numbers[counter] <- n
# make next Collatz number
n <- collatzRule(n)
}
# find how many Collatz numbers we made:
howMany <- min(counter, limit)
# print them out:
print(numbers[1:howMany])
}
datalist = list()
for (i in 2:100) {
# ... make some data
dat <- collatz(i) %>% as.data.frame()
dat$i <- i %>% as.factor() # maybe you want to keep track of which iteration produced it?
datalist[[i]] <- dat # add it to your list
}
big_data = do.call(rbind, datalist)
这会产生一个看起来像这样的数据框:
. i
1 2 2
2 3 3
3 10 3
4 5 3
5 16 3
6 8 3
我想添加一个看起来像这样的列。
. i x
1 2 2 1
2 3 3 1
3 10 3 2
4 5 3 3
5 16 3 4
6 8 3 5
任何帮助将不胜感激!
最良好的祝愿