【发布时间】:2019-11-09 18:56:58
【问题描述】:
我尝试通过 3 个自定义函数循环 df 元素列表。当我手动运行每个 df 但应用 lapply 失败时,它可以工作。 仅供参考:结果应该会导致“扩展”每个数据集,我稍后将使用它来裁剪图像文件。数据 txt 文件具有 .swc 扩展名,但只是 txt 文件。 当我手动通过函数运行数据集时,它可以工作。然后我 将多个文件导入到一个列表中,这也有效。 但是,当我尝试使用 lapply 通过函数运行每个列表元素时,出现以下错误
这是应用 lapply 的实际尝试
result<-lapply(df_swc_list, fxn(x))
练习使用 dfs 并导入到列表中
df_swc1 <- data.frame(V1 = c(1,2,3,4), V2 = c(17.2,17.2,18.2,18.2),
V3=c(105.32,106.01,108.89,109.99), V4=c(3,4,4,6), V5=c(1,2,2,2),
V6=c(7,7,7,7), V7=c(-1,0,1,2))
df_swc2 <- data.frame(V1 = c(1,2,3,4), V2 = c(17.2,17.2,18.2,18.2),
V3=c(105.32,106.01,108.89,109.99), V4=c(5,5,4,5), V5=c(1,2,2,2),
V6=c(7,7,7,7), V7=c(-1,0,1,2))
df_swc_list <- list(df_swc1,df_swc2)
df_swc_list_names<-c("control", "variable")
names(df_swc_list)<-gsub("\\.swc$", "",df_swc_list_names)
pythag.opp.leg<-function(Radius){
Diam<-Radius*2
opposite<-sqrt((Diam^2)/2)
opposite.rounded<-round(opposite)
box<-opposite.rounded/2
return(box)
}
swc.fxn <-function(df1){
box<- round(pythag.opp.leg(df1$Radius))
swc.box<- Map(function(a, b, c, d, e) data.frame(X = a:b, Y = c:d, Z = e),
df1$X-box, df1$X+box, df1$Y-box, df1$Y+box, df1$Z)
swc.box2<- purrr::map_df(swc.box, function(x) tidyr::expand(x, X, Y, Z))
return(swc.box2)
}
swc_process_A<-function(x){
as.data.frame(x)->swc2
swc2[,2:6]->swc3
swc3$V2->swc3$Type
swc3$V3->swc3$X
swc3$V4->swc3$Y
swc3$V5->swc3$Z
swc3$V6->swc3$Radius
swc3[,6:10]->swc4
trunc(swc4$X)->swc4$X
trunc(swc4$Y)->swc4$Y
trunc(swc4$Z)->swc4$Z
swc4->swc5
as.data.frame((swc.fxn(swc5)))->expanded.swc.df2
return(expanded.swc.df2)
}
尝试应用 lapply 循环
`result<-lapply(df_swc_list, swc_process_A(x))`
df_swc1 的预期结果(列表中的第一个 df 元素)
str(expanded.swc.df)
data.frame':484 obs。 3 个变量:
X: 整数 100 100 100 100 100 100 100 100 100 100 ...
Y: int -2 -1 0 1 2 3 4 5 6 7 ...
Z: 数字 1 1 1 1 1 1 1 1 1 1 ...
实际错误消息显示错误在
[.data.frame`(swc3, , 6:10) : 选择了未定义的列
【问题讨论】:
-
当你尝试循环运行时会发生什么?
-
此错误消息:[.data.frame`(swc3, , 6:10) : undefined columns selected
-
lapply 电话不应该是
lapply(df_swc_list, "swc_process_A")吗? -
你说得对。那成功了。谢谢!
-
您能否将其添加到“答案”部分,以便我将其列为正确答案并给予您奖励