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)
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)
sprintf("('%s', %d)", df[[1]], df[[2]])
# [1] "('asd', 23)" "('dsf', 354)" "('fds', 45)" "('gfd', 32)"
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