【发布时间】:2021-10-19 04:18:54
【问题描述】:
我有一个list 或data.frames。我想使用lapply 将每个data.frame 发送到function。在function 内部,我想检查data.frame 的name 是否包含特定的string。如果有问题的string 存在,我想执行一系列操作。否则我想执行一系列不同的操作。我不知道如何检查string 是否存在于function 中。
我希望使用基础R。这似乎是一个可能的解决方案,但我无法让它工作:
In R, how to get an object's name after it is sent to a function?
这是一个示例list,后面是一个示例function。
matrix.apple1 <- read.table(text = '
X3 X4 X5
1 1 1
1 1 1
', header = TRUE)
matrix.apple2 <- read.table(text = '
X3 X4 X5
1 1 1
2 2 2
', header = TRUE)
matrix.orange1 <- read.table(text = '
X3 X4 X5
10 10 10
20 20 20
', header = TRUE)
my.list <- list(matrix.apple1 = matrix.apple1,
matrix.orange1 = matrix.orange1,
matrix.apple2 = matrix.apple2)
这个操作可以检查每个对象name是否包含stringapples
但我不确定如何在下面的function 中使用这些信息。
grepl('apple', names(my.list), fixed = TRUE)
#[1] TRUE FALSE TRUE
这是一个示例function。基于数小时的搜索和反复试验,我可能应该使用 deparse(substitute(x)),但到目前为止它只返回 x 或类似的东西。
table.function <- function(x) {
# The three object names are:
# 'matrix.apple1', 'matrix.orange1' and 'matrix.apple2'
myObjectName <- deparse(substitute(x))
print(myObjectName)
# perform a trivial example operation on a data.frame
my.table <- table(as.matrix(x))
# Test whether an object name contains the string 'apple'
contains.apple <- grep('apple', myObjectName, fixed = TRUE)
# Use the result of the above test to perform a trivial example operation.
# With my code 'my.binomial' is always given the value of 0 even though
# 'apple' appears in the name of two of the data.frames.
my.binomial <- ifelse(contains.apple == 1, 1, 0)
return(list(my.table = my.table, my.binomial = my.binomial))
}
table.function.output <- lapply(my.list, function(x) table.function(x))
这些是print(myObjectName)的结果:
#[1] "x"
#[1] "x"
#[1] "x"
table.function.output
这是table.function 的其余结果,表明my.binomial 始终为0。
my.binomial 的第一个和第三个值应该是1,因为第一个和第三个data.frames 的names 包含string apple。
# $matrix.apple1
# $matrix.apple1$my.table
# 1
# 6
# $matrix.apple1$my.binomial
# logical(0)
#
# $matrix.orange1
# $matrix.orange1$my.table
# 10 20
# 3 3
# $matrix.orange1$my.binomial
# logical(0)
#
# $matrix.apple2
# $matrix.apple2$my.table
# 1 2
# 3 3
# $matrix.apple2$my.binomial
# logical(0)
【问题讨论】: