2017-03-02 122 views
0

目前我有一個循環將一行數據框中的行添加到另一個主數據框中。不幸的是,它將字符轉換爲數字,但我不想那樣。如何獲得以下for循環以將一個數據框中的行添加到主數據框中,同時保留字符?在For循環中填充包含字符的數據幀R

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 

回答

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 
      } 
+0

真棒!謝謝user3640617! – albeit2