Extract Rows and Place Into New Columns.

I am trying to extract rows and place these groups of rows into columns. The rows I need to extract are of uneven length. Not sure how to specify the conditions and apply the loop (?).

Here is the dataset I'm working with:

Data1 <- data.frame("Example" = c("Word A", "URL", "URL", "URL",
                                  "Word B", "URL",
                                  "Word C", "URL", "URL"))

I want it to look like this:

Data2 <- data.frame("Example 1" = c("Word A", "URL", "URL", "URL"),
                    "Example 2" = c("Word B", "URL", NA,  NA),
                    "Example 3" = c("Word C", "URL", "URL",  NA))

Thanks anyone who can help!

Here is one way.

Data1 <- data.frame("Example" = c(
  "Word A", "URL", "URL", "URL",
  "Word B", "URL",
  "Word C", "URL", "URL"
))



Data2 <- data.frame(
  "Example 1" = c("Word A", "URL", "URL", "URL"),
  "Example 2" = c("Word B", "URL", NA, NA),
  "Example 3" = c("Word C", "URL", "URL", NA)
)

library(dplyr)
library(purrr)
Data1$wcount <- cumsum(startsWith(Data1$Example, "W"))

(components <- group_by(
  Data1,
  wcount
) %>% group_map(.f = function(x, ...) as.matrix(x)))

(components <- imap(
  components,
  ~ {
    colnames(.x) <- paste0("Example ", .y)
    .x
  }
))

(height <- max(map_int(components, nrow)))

(padded_components <- map(components, ~ {
  if (nrow(.x) < height) {
    # need to padd
    padder <- matrix(NA_character_, nrow = height - nrow(.x))
  } else {
    padder <- matrix(NA_character_, nrow = 0, ncol = 1)
  }
  rbind(.x, padder)
}))

as.data.frame(reduce(padded_components, cbind))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.