希望在小标题中的单个列上将apply()系列用于客户功能
我已经阅读了许多与apply()相关的问题,但到目前为止,它们似乎比我尝试的要复杂。
library(dplyr)
library(stringr)
sample <- tibble(
id = 1:13,
NodeName = c("Tree", "Rock", "Cloud", "Tree.Maple", "Tree.Oak", "Tree.Ash", "Rock.Igneous", "Rock.Sedimentary", "Rock.Metamorphic", "Cloud.Cumulus", "Cloud.Nimbus", "Cloud.Stratus", "Cloud.Cirrus"),
NodeType = c("Table", "Table", "Table", "Column", "Column", "Column", "Column", "Column", "Column", "Column", "Column", "Column", "Column")
)
GetTableName2 <- function(tibbleName, rowNum){
columnName <- unlist(tibbleName[rowNum, 2])
dotPosition <- str_locate(columnName, "[.]")[1]
if(!is.na(dotPosition)){
return(str_sub(columnName, start=1, end=dotPosition - 1))
}else{
NA
}
}
GetParentID <- function(tibbleName, rowNum){
tibbleName %>%
filter(NodeName == GetTableName2(tibbleName, rowNum)) %>%
select(id) %>%
unlist
}
GetParentID(sample, 11)
apply(sample[,2], MARGIN=2, FUN=GetParentID)
当我自己运行该函数时,我得到了预期的输出:3 当我使用apply()函数尝试它时,出现此错误:
Error in UseMethod("filter_") :
no applicable method for 'filter_' applied to an object of class "character"
trace:
filter_(.data, .dots = compat_as_lazy_dots(...))
filter.default(., NodeName == GetTableName2(tibbleName, rowNum))
filter(., NodeName == GetTableName2(tibbleName, rowNum))
function_list[[i]](value)
freduce(value, `_function_list`)
`_fseq`(`_lhs`)
eval(quote(`_fseq`(`_lhs`)), env, env)
eval(quote(`_fseq`(`_lhs`)), env, env)
withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
tibbleName %>% filter(NodeName == GetTableName2(tibbleName, rowNum)) %>%
select(id) %>% unlist
FUN(newX[, i], ...)
apply(sample[, 2], MARGIN = 2, FUN = GetParentID)
我承认apply()系列对我来说是一个反复出现的难题。每当我认为得到它,然后在几周或几个月后再回到它时,我都会面临我确实没有“得到它”的证据。
感谢您的关注。