R: losing column names when adding rows to an empty data frame

前端 未结 8 1169
旧时难觅i
旧时难觅i 2020-12-05 01:36

I am just starting with R and encountered a strange behaviour: when inserting the first row in an empty data frame, the original column names get lost.

example:

8条回答
  •  天涯浪人
    2020-12-05 01:58

    was almost surrendering to this issue.

    1) create data frame with stringsAsFactor set to FALSE or you run straight into the next issue

    2) don't use rbind - no idea why on earth it is messing up the column names. simply do it this way:

    df[nrow(df)+1,] <- c("d","gsgsgd",4)

    df <- data.frame(a = character(0), b=character(0), c=numeric(0))
    
    df[nrow(df)+1,] <- c("d","gsgsgd",4)
    
    #Warnmeldungen:
    #1: In `[<-.factor`(`*tmp*`, iseq, value = "d") :
    #  invalid factor level, NAs generated
    #2: In `[<-.factor`(`*tmp*`, iseq, value = "gsgsgd") :
    #  invalid factor level, NAs generated
    
    df <- data.frame(a = character(0), b=character(0), c=numeric(0), stringsAsFactors=F)
    
    df[nrow(df)+1,] <- c("d","gsgsgd",4)
    
    df
    #  a      b c
    #1 d gsgsgd 4
    

提交回复
热议问题