Question

I would like to create a column that contains the objects names inside a lapply function, as a proxy I call it name.of.x.as.strig.function(), unfortunately I am not sure how to do it, maybe a combination of assign, do.call and paste. But so far using this function only led my into deeper troubles, I am quite sure there is a more R like solution.

# generates a list of dataframes, 
data <- list(data.frame(c(1,2),c(3,3)),data.frame(c(1,2),c(3,3)),data.frame(c(1,2),c(3,3)),data.frame(c(1,2),c(3,3)))

# assigns names to dataframe
names(data) <- list("one","two", "tree", "four")

# subsets the second column into the object data.anova
data.anova <- lapply(data, function(x){x <- x[[2]];                                        
                                       return(matrix(x))})

This should allow me to create a column inside the dataframe that contains its name, for all matrices inside the list

data.anova <- lapply(data, function(x){    
    x$id <- name.of.x.as.strig.function(x)
    return(x)})

I would like to retrieve:

3 one
3 one

3 two
3 two

...

Any input is highly appreciated.

Search history: function to retrieve object name as string, R get name of an object inside lapply...

Was it helpful?

Solution

Can it be that you are just looking for stack?

stack(lapply(data, `[[`, 2))
#   values  ind
# 1      3  one
# 2      3  one
# 3      3  two
# 4      3  two
# 5      3 tree
# 6      3 tree
# 7      3 four
# 8      3 four

(Or, using your original approach: stack(lapply(data, function(x) {x <- x[[2]]; x})))

If this is the case, melt from "reshape2" would also work.

OTHER TIPS

Loop through the indices of data.anova, and use that to fetch both the data and the names:

data.anova <- lapply(seq_along(data.anova), function(i){    
  x <- as.data.frame(data.anova[[i]])
  x$id <- names(data.anova)[i]
  return(x)})  

This produces:

# [[1]]
#   V1  id
# 1  3 one
# 2  3 one

# [[2]]
#   V1  id
# 1  3 two
# 2  3 two

# [[3]]
#   V1   id
# 1  3 tree
# 2  3 tree

# [[4]]
#   V1   id
# 1  3 four
# 2  3 four
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top