Say I have an R list like this:
> summary(data.list)
Length Class Mode
aug9104AP 18 data.frame list
Aug17-10_acon_7pt_dil_series_01 18 data.frame list
Aug17-10_Picro_7pt_dil_series_01 18 data.frame list
Aug17-10_PTZ_7pt_dil_series_01 18 data.frame list
Aug17-10_Verat_7pt_dil_series_01 18 data.frame list
I want to process each data.frame in the list using l_ply
, but I also need the name (e.g. aug9104AP) to be passed into the processing function along with the data.frame. Something like:
l_ply(data.list,function(df,...) {
cli.name<- arg_to_access_current_list_item_name
#make plots with df, use cli.name in plot titles
#save results in a file called cli.name
}, arg_to_access_current_list_item_name
)
What should arg_to_access_current_list_item_name
be?
If you need to 'name' a div in order to address it from javascript or otherwise uniquely identify it on a page, you can use the id attribute. That said, most modern browsers will handle a name attribute on a div with no issues but it does not conform to HTML standards.
The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list.
From R base functionality, we have colnames() and names() functions that can be used to rename columns from the list. These functions are used to set or get the names of a dataframe object. You can also use setnames() to change old column names with new columns from the list.
You can use do. call() in R to apply a given function to a list as a whole.
It's easiest to start with the names, and then use them to extract the bit you're interested in:
l_ply(names(data.list),function(name,...) {
df <- data.list[[name]]
)
You can also use m_ply
to pass in both the name and data:
m_ply(cbind(names(data.list), data.list), function(name, df, ...) {
...
}
In case you pass them one by one, you can use deparse(substitute(arg)) , eg :
test <- function(x){
y <- deparse(substitute(x))
print(y)
print(x)
}
var <- c("one","two","three")
test(var)
[1] "var"
[1] "one" "two" "three"
for l_ply, you'll have to resort to add the attribute to the list itself eg :
for(i in 1:length(data.list)){
attr(data.list[[i]],"name") <- names(data.list)[i]
}
Then you can use attr :
cli <- attr(x,"name")
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With