【问题标题】:How to fix the error "there are more elements are supplied than there are to replace" in a for loop in R?如何修复R中for循环中的错误“提供的元素多于替换的元素”?
【发布时间】:2020-09-08 16:06:08
【问题描述】:

有人可以帮我解决这个问题吗?我让 cut_interval 代码为单个测试列工作,但似乎无法让它在 for 循环中工作以使其在所有列上运行。

#Bin worker data into three groups (low/medium/high %methylation) for the cpg cg10757709
#This code works
cg10757709_interval <- cut_interval(cpgs$cg10757709, n=3, labels = c("low","med","high"))
View(cg10757709_interval)

#Write a loop so that data for each of the significant cpgs will be binned into low, medium, and high groups
#This code gives an error (that there are more elements are supplied than there are to replace)
cpgs_interval <- matrix(ncol = length(cpgs), nrow = 29) 
for (i in seq_along(cpgs)) {
  cpgs_interval[[i]] <- cut_interval(cpgs[[i]], n=3, labels = c("low","med","high"))
}
View(cpgs_interval)

错误显示“cpgs_interval[[i]]

【问题讨论】:

    标签: r for-loop ggplot2


    【解决方案1】:

    在您的示例中,cpgs_interval 是一个矩阵。如果要将变量放入矩阵的第 i 列,可以这样做:

    for (i in seq_along(cpgs)) {
      cpgs_interval[,i] <- cut_interval(cpgs[[i]], n=3, labels = c("low","med","high"))
    }
    

    也就是说,您最好将cpgs_interval 设为数据框,然后您将保留该因子而不是将其转换为文本。

    【讨论】:

    • 谢谢。将 data.frame 添加到 cpgs_interval 就可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2022-01-11
    • 2021-06-18
    相关资源
    最近更新 更多