Skip to content
Prev 244490 / 398503 Next

lapply getting names of the list

Thanks a lot Joshua, that works perfectly fine. 
I could not think to lapply on the names instead of data itself.
I don't now notice SampleID names in the column names.
Thanks for your time,

-Sashi

-----Original Message-----
From: Joshua Wiley [mailto:jwiley.psych at gmail.com] 
Sent: Thursday, December 09, 2010 10:07 AM
To: Sashi Challa
Cc: r-help at R-project.org
Subject: Re: [R] lapply getting names of the list

Hi Sashi,
On Thu, Dec 9, 2010 at 9:44 AM, Sashi Challa <challa at ohsu.edu> wrote:
correct, names() returns the top level names of infile.split (i.e.,
the two data frame names)
It is a single, named list containing two data frames (A1 and B1)
(though data frames are built from lists, I think so I suppose in a
way it contains two lists, but that is not really the point).
by using lapply() on the actual object, your function is getting each
element of the list.  That is:

infile.split[[1]]
infile.split[[2]]

trying names() on those:

names(infile.split[[1]])

should show what you are getting
FYI I think you are missing a parenthesis in there somewhere
Try this:

## read your data from the clipboard (obviously you do not need to)
infile <- read.table("clipboard", header = TRUE)
split.infile <- split(dat, dat$SampleID) #split data
path <- "~" # generic path

## rather than applying to the data itself, instead apply to the names
lapply(names(split.infile), function(x) {
  write.table(x = split.infile[[x]],
    file = paste(path, paste(x, "toy_set.txt", sep = "_"), sep = "/"),
    row.names = FALSE, quote = FALSE, sep = "\t")
  cat("wrote ", x, fill = TRUE)
})

it will return two NULL lists, but that is fine because it should have
written the files.
Can you report the results of str(yourdataframe) ?  I did not have
that issue just copying and pasting from your email and using the code
I showed above.

Cheers,

Josh