Reputation: 407
My data frame:
df <- structure(list(g1 = 1:12, g2 = c(3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 11L, 12L, 13L, 67L)), class = "data.frame", row.names = c(NA,
-12L))
I would like to combine 2 columns of my data frame and get a list of vectors
What I want to get:
list(c("1","3"),c("2","4"),c("3","5"),c("4","6"),c("5","7"),c("6","8"),c("7","9")c("8","10"),c("9","11"),c("10","12"),c("11","13"),c("12","67"))
What I tried:
mark.list <- list()
for(i in 1:length(bact$group1)){
x <- bact$group1[i]
y <- bact$group2[i]
df <- combn(paste(x,y))
mark.list <- c(mark.list,df)
}
Upvotes: 3
Views: 221
Reputation: 886948
Using pmap
library(purrr)
pmap(df, ~ unname(c(...)))
-output
[[1]]
[1] 1 3
[[2]]
[1] 2 4
[[3]]
[1] 3 5
[[4]]
[1] 4 6
[[5]]
[1] 5 7
[[6]]
[1] 6 8
[[7]]
[1] 7 9
[[8]]
[1] 8 10
[[9]]
[1] 9 11
[[10]]
[1] 10 12
[[11]]
[1] 11 13
[[12]]
[1] 12 67
Upvotes: 1
Reputation: 101064
Another base R option
> unclass(data.frame(t(df)))
$X1
[1] 1 3
$X2
[1] 2 4
$X3
[1] 3 5
$X4
[1] 4 6
$X5
[1] 5 7
$X6
[1] 6 8
$X7
[1] 7 9
$X8
[1] 8 10
$X9
[1] 9 11
$X10
[1] 10 12
$X11
[1] 11 13
$X12
[1] 12 67
attr(,"row.names")
[1] "g1" "g2"
If you want to have output with characters, you can try
> strsplit(do.call(paste, df), " ")
[[1]]
[1] "1" "3"
[[2]]
[1] "2" "4"
[[3]]
[1] "3" "5"
[[4]]
[1] "4" "6"
[[5]]
[1] "5" "7"
[[6]]
[1] "6" "8"
[[7]]
[1] "7" "9"
[[8]]
[1] "8" "10"
[[9]]
[1] "9" "11"
[[10]]
[1] "10" "12"
[[11]]
[1] "11" "13"
[[12]]
[1] "12" "67"
Upvotes: 4
Reputation: 631
ls=list(c("1","3"),c("2","4"),c("3","5"),c("4","6"),c("5","7"),c("6","8"),c("7","9"),c("8","10"),c("9","11"),c("10","12"),c("11","13"),c("12","67"))
vec <- c()
ls=list()
for (k in 1:nrow(df)){
print(k)
vec <- c(c(as.character(df$g1[k]),as.character(df$g2[k])))
ls[k] <- list(vec)
}
output
> ls
[[1]]
[1] "1" "3"
[[2]]
[1] "2" "4"
[[3]]
[1] "3" "5"
[[4]]
[1] "4" "6"
[[5]]
[1] "5" "7"
[[6]]
[1] "6" "8"
[[7]]
[1] "7" "9"
[[8]]
[1] "8" "10"
[[9]]
[1] "9" "11"
[[10]]
[1] "10" "12"
[[11]]
[1] "11" "13"
[[12]]
[1] "12" "67"
Upvotes: 2
Reputation: 388817
Here are couple of base R options -
asplit
asplit(df, 1)
as.list
.t(df) |> as.data.frame() |> as.list() |> unname()
Upvotes: 4