rg4s
rg4s

Reputation: 897

How do I map (match) columns and rows in a dataframe?

I have parsed data to columns from Coursera web-site. I have 6 columns, all of them are different in length, but I need to properly map them to form a dataframe. I can't do this with cbind.fill() from rowr package. I can't neither do this with simple cbind.data.frame() nor data.table() (from data.table package).

Here's the sample code.

   c1 <- c("one", "two", "three", "four")
   c2 <- c("55k", "98m", 340k")
   c3 <- c("Toronto University", "NYU", "Yale", "Harvard")
   c4 <- c("Beginner", "Intermediate")

   data <- rowr::cbind.fill(c1, c2, c3, c4, fill = NA) # does not match the vars
   data <- cbind.data.frame(c1, c2, c3, c4) # does not match the vars, either
   data <- data.table(c1, c2, c3, c4) # the same situation

I need to recieve df like this:

   c1    c2    c3                   c4 
  one    55k   Toronto University   Beginner
  two    98m   NYU                  Intermediate
  three  349k  Yale                 NA
  four   NA    Harvard              NA

Upvotes: 0

Views: 109

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389275

Put the vectors in a list. Get the max length of list and subset.

list_vec <- list(c1, c2, c3, c4)
as.data.frame(sapply(list_vec, `[`, seq_len(max(lengths(list_vec)))))

#     V1   V2                 V3           V4
#1   one  55k Toronto University     Beginner
#2   two  98m                NYU Intermediate
#3 three 340k               Yale         <NA>
#4  four <NA>            Harvard         <NA>

Upvotes: 3

Related Questions