albeit2
albeit2

Reputation: 93

Populating a Data Frame with Characters in a For Loop R

Currently I have a loop that is adding rows from one data frame into another master data frame. Unfortunately, it converts the characters into numbers, but I don't want that. How can I get the following for loop to add the rows from one data frame into the master data frame while keeping the characters?

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]]
}

So what I would like to come out of this is:

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

Upvotes: 0

Views: 303

Answers (1)

user3640617
user3640617

Reputation: 1576

This should work:

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
             }

Upvotes: 1

Related Questions