《R语言实战》中有如下函数:
table2flat <- function(mytable) {
df <- as.data.frame(mytable)
rows <- dim(df)[1]
cols <- dim(df)[2]
x <- NULL
for (i in 1:rows) {
for (j in 1:df$Freq[i]) {
row <- df[i, c(1cols - 1))]
x <- rbind(x, row)
}
}
row.names(x) <- c(1:dim(x)[1])
return(x)
}
测试输入:
treatment <- rep(c("lacebo", "Treated"), 3)
improved <- rep(c("None", "Some", "Marked"), each = 2)
Freq <- c(29, 13, 7, 7, 7, 21)
mytable <- as.data.frame(cbind(treatment, improved, Freq))
mydata <- table2flat(mytable)
问题:
for (j in 1:df$Freq[i]){}
这个循环执行次数不是我理解的根据Freq <- c(29, 13, 7, 7, 7, 21)随着外层循环分别执行29, 13, 7, 7, 7, 21次?
实际发现当i为1时,这个循环只执行了3次
|