R dataframe with varied column lengths

前端 未结 2 1140
野的像风
野的像风 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
    

提交回复
热议问题