Question

Suppose I have a list of vectors (s) containing sublists of integers.

> s #List of 2 integers

> [[1]]
> [1]    23 900 1800 42 87

> [[2]]
> [1]    54 8777 13 1 2 3

The integers correspond to the row number within a dataframe containing characters, separated by " ".

> origninaldf

>[1,] "Apple"
>[2,] "Apples"
>[3,] "123_Street"

I would like to convert the list to a new dataframe (newdf) retaining the sublist number and row numbers (s) converted to characters based on dataframe (orignaldf).

> newdf
1   Zoo  ...
2   ... ... ... Apple Apples 123_Street

Thank you! (Still very new to coding within R)

Was it helpful?

Solution

Perhaps:

lapply(s,  function(i) originaldf[ i[ i %in% 1:length(originaldf) ] ] )

Unclear what you mean by "retaining the sublist number", since operations are rarely destructive and the numbers do not appear in your desired result. Also you show an output with varying numbers of elements which would generally need to ba list or a text file. Further confusion is caused by the output of 'originadf' which is being displayed as though it is not a dataframe but rather a matrix.

s <- list(c(23, 900, 1800, 42, 87), c(54, 8777, 13, 1, 2, 3))
origninaldf <- 

structure(list(nam = structure(c(2L, 3L, 1L), .Label = c("123_Street", 
"Apple", "Apples"), class = "factor")), .Names = "nam", row.names = c(NA, 
-3L), class = "data.frame")

> lapply(s,  function(i) origninaldf[ i[ i %in% 1:length(origninaldf)] ] )
[[1]]
data frame with 0 columns and 3 rows

[[2]]
         nam
1      Apple
2     Apples
3 123_Street
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top