-2

I have a dataframe df, where I need to get the values as vector like shown below. Is it possible to achieve?

df
ColA  ColB
asd     23
dsf     354
fds     45
gfd     32

Expected output

('asd',23) ('dsf', 354) ('fds', 45) ('gfd', 32)
manish p
  • 177
  • 6

2 Answers2

2
sprintf("('%s', %d)",  df[[1]], df[[2]])
# [1] "('asd', 23)"  "('dsf', 354)" "('fds', 45)"  "('gfd', 32)" 
s_baldur
  • 29,441
  • 4
  • 36
  • 69
1

You cannot create an atomic vector with the given structure because you have mixed data types and a nested structure. At least, that is how I interpret your required output.

The crude solution uses a loop and a growing list. That is neither elegant nor fast but it gets the job done. Note the argument stringAsFactors in the df assignment. If your data frame interpreted ColA as factor the result will look different. You have to make sure it is not a factor but a character column.

df <- data.frame(ColA = c("asd", "dsf", "fds", "gfd"), 
                 ColB = c(23, 354, 45, 32), 
                 stringsAsFactors = FALSE)
result <- list()
for (r in 1:nrow(df)) {
  result <- c(result, df[r,])
}
result

A more elegant solution uses mapply.

result <- mapply(function(x, y) list(x, y), df$ColA, df$ColB)
result
Jan
  • 4,974
  • 3
  • 26
  • 43