Right way to convert data.frame to a numeric matrix, when df also contains strings?

前端 未结 6 641
说谎
说谎 2020-12-22 19:34

I have a data frame taken from a .csv-file which contains numeric and character values. I want to convert this data frame into a matrix. All containing information is number

6条回答
  •  失恋的感觉
    2020-12-22 19:40

    I manually filled NAs by exporting the CSV then editing it and reimporting, as below.

    Perhaps one of you experts might explain why this procedure worked so well (the first file had columns with data of types char, INT and num (floating point numbers)), which all became char type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).

    # STEP 1:
    MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
                                header=T, stringsAsFactors=FALSE)
    #... STEP 2:
    TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
    write.csv(TestFrame, file = "TestFrame2.csv")
    # ...
    # STEP 3:
    # I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:    
    XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
                                header=T,stringsAsFactors=FALSE)
    

    On arrival back in R, all columns had their correct measurement levels automatically recognized by R!

提交回复
热议问题