user8840683
user8840683

Reputation:

Extracting the names of a list of data.frames along with values in the data.frame in R

In below code, j is a named list of data.frames. I was wondering if there might be a way to:

(a) extract the numeric values of the variables (i.e., one.short and one.long) inside the data.frames and attach their related names (i.e., "AAA" or "BBB" or "CCC") to the extracted values?

(b) if a variable (i.e., one.short or one.long) is NA, then change the name of that data.frame to NA when extracting that variable?

Expected output:

In the below example, I expect my output to be like:

one.short = list(c("AAA", .6), c(NA, NA), c("CCC", .4))

one.long = list(c("AAA", .8), c(NA, NA), c(NA, NA))

R Code and reproducible data:

j <- list(data.frame(one.short = .6, one.long = .8), data.frame(one.short = NA, 
one.long = NA), data.frame(one.short = .4, one.long = NA))

names(j) <- c("AAA", "BBB", "CCC")

# I tried this without success:
one.short = sapply(1:length(j), function(i) j[[i]]$one.short)
one.long  = sapply(1:length(j), function(i) j[[i]]$one.long)

Upvotes: 2

Views: 530

Answers (2)

akrun
akrun

Reputation: 886998

We can use the [[ to do this without anonymous function

v1 <- sapply(j, `[[`, 'one.short')
v1
#  AAA BBB CCC 
# 0.6  NA 0.4 

If we want to set the names of values that NA

names(v1)[is.na(v1)] <- "NULL"
v1
#   AAA NULL  CCC 
#  0.6   NA  0.4 

Note that NULLwould need to be in a list because it gets dropped in a vector

c('a', 'b', NULL)
#[1] "a" "b"   


list('a', 'b', NULL)
#[[1]]
#[1] "a"

#[[2]]
#[1] "b"

#[[3]]
#NULL

Upvotes: 1

Nate
Nate

Reputation: 10671

Here is the base version, all you need is the intermediate assigment to make it work.

j_short <- sapply(names(j), function(x) j[[x]]$one.short)

j_short <- setNames(j_short, ifelse(is.na(j_short), NA, names(j_short)))

j_short
AAA BBB CCC 
0.6  NA 0.4 

Upvotes: 0

Related Questions