R dataframe with varied column lengths

前端 未结 2 1123
野的像风
野的像风 2020-12-17 06:09

I have a dataframe with 10 rows

df <- c(1:10)

How do I add another column to the dataframe which has only 5 rows?

df2 &l         


        
相关标签:
2条回答
  • 2020-12-17 06:45

    There are two approaches I know of to get what you're asking for BUT this may not be the best approach to the problem as others have pointed out. What I'm going to show you I myself would not use (I'd opt for the list option most likely as Tim shows).

    df <- data.frame(var=1:10)  #notice I created a data.frame vs. the vector you called
    new.col <- c(1:5)
    
    #METHOD 1
    df$new.col <- c(new.col, rep(NA, nrow(df)-length(new.col)))  #keep as integer
    #METHOD 2
    df$new.col2 <- c(new.col, rep("", nrow(df)-length(new.col))) #converts to character
    df                                         #look at it
    str(df)                                    #see what's happening to the columns
    
    0 讨论(0)
  • 2020-12-17 07:00

    I'll give some little pointers here. See Tyler's answer a few questions back for a couple links to materials for getting started: convert data.frame column format from character to factor

    1) The objects you're making with c() are called vectors, and that is a particular kind of object in R- the most basic and useful kind.

    2) A data.frame is a kind of list where all the elements of the list are stuck together as columns and must be of the same length. The columns can be different data types (classes)

    3) lists are the most versatile kind of object in R- the elements of a list can be anything- any size, any class. This appears to be what you're asking for.

    So for instance:

        mylist <- list(vec1 = c(1:10), vec2 = c(1:5))
        mylist
        $vec1
         [1]  1  2  3  4  5  6  7  8  9 10
        $vec2
         [1] 1 2 3 4 5
    

    There are different ways to get back at the elements of mylist, e.g.

        mylist$vec1
        mylist[1]
        mylist[[1]]
        mylist["vec1"]
        mylist[["vec1"]]
    

    and likely more! Find a tutorial by searching for 'R beginner tutorial' and power through it. Have fun!

    0 讨论(0)
提交回复
热议问题