3

I would like to convert a data frame into a list. See input in Table 1. See the output in Table 2. When you open a list in R from the environment. Name - the following names clus1, clus2... Type - should contain values from column V1 Value - list of length 3

Table 1
      V1 V2 V3
clus1 10 a  d
clus2 20 b  e
clus3 5  c  f

Table 2
$`clus1`
[1] "a"  "d" 

$`clus2`
[2] "b"  "e" 

$`clus3`
[2] "c"  "f"
1
  • can you share dput(table1)? Commented Oct 29, 2019 at 14:36

2 Answers 2

7
t1 = read.table(text = "      V1 V2 V3
clus1 10 a  d
clus2 20 b  e
clus3 5  c  ''", header = T)

result = split(t1[, 2:3], f = row.names(t1))
result = lapply(result, function(x) {
  x = as.character(unname(unlist(x)))
  x[x != '']})
result
# $clus1
# [1] "a" "d"
# 
# $clus2
# [1] "b" "e"
# 
# $clus3
# [1] "c"

In this particular case, we can go a bit more directly if we convert to matrix first:

r2 = split(as.matrix(t1[, 2:3]), f = row.names(t1))
r2 = lapply(r2, function(x) x[x != ''])
# same result
Sign up to request clarification or add additional context in comments.

4 Comments

Do you know how to omit empty cells in a list which are in the original data frame t1?
I don't know what you mean by "empty spots". Missing values, with NA? Blanks, with ""? Something else?
sorry, blanks with ""
lapply(t1, function(x) x[!x %in% ""])
2

You might think of this as a reshaping task in order to scale it for multiple columns, i.e. create a column of values rather than tracking throughout that you're working with columns V2 and V3. That way, you can do it in one pass with some basic tidyverse functions. This also lets you easily filter the data before making the list, based on removing blanks or any other condition, again without specifying columns.

library(dplyr)

# thanks @Gregor for filling in the data
tibble::rownames_to_column(t1, var = "clust") %>%
  select(-V1) %>%
  tidyr::gather(key, value, -clust) %>%
  filter(value != "") %>%
  split(.$clust) %>%
  purrr::map("value")
#> $clus1
#> [1] "a" "d"
#> 
#> $clus2
#> [1] "b" "e"
#> 
#> $clus3
#> [1] "c"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.