【问题标题】:Populating a Data Frame with Characters in a For Loop R用 For 循环 R 中的字符填充数据帧
【发布时间】:2017-03-02 16:04:18
【问题描述】:

目前我有一个循环将行从一个数据帧添加到另一个主数据帧。不幸的是,它将字符转换为数字,但我不希望这样。如何在保留字符的同时获得以下 for 循环以将一个数据帧中的行添加到主数据帧中?

AnnotationsD <- data.frame(x = vector(mode = "numeric", 
  length = length(x)), type = 0, label = 0, lesion = 0)

x = c(1,2)

for(i in length(x)){
D = data.frame(x = i, type = c("Distance"), 
  label = c("*"), lesion = c("Wild"))

AnnotationsD[[i,]] <- D[[i]]
}

所以我想从中得出的结论是:

   x  type      label  lesion
1  1  Distance  *      Wild
2  2  Distance  *      Wild

【问题讨论】:

    标签: r for-loop dataframe character


    【解决方案1】:

    这应该可行:

    x = c(1,2)
    AnnotationsD <- data.frame(x = as.character(NA), type = as.character(NA),
                               label = as.character(NA), lesion = as.character(NA),
                               stringsAsFactors =F)
    
    for(i in 1:length(x)){
                 D = c(x = as.character(i), type = as.character("Distance"), 
                 label = as.character("*"), lesion = as.character("Wild"))
    
                 AnnotationsD[i,] <- D
                 }
    

    【讨论】:

    • 太棒了!谢谢user3640617!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多