【发布时间】:2017-06-14 10:55:58
【问题描述】:
问题:
对于如何对数据框列表中的列进行批处理 as.numeric() (或与此相关的任何其他函数),我感到有些困惑。
我了解我可以通过以下方式查看此列表中的特定数据框或列:
> my.list[[1]]
# or columns within this data frame using:
> my.list[[1]][1]
但是当我尝试将其应用于 lapply() 函数以将所有数据从整数更改为数字时,麻烦就来了。
# Example of what I am trying to do
> my.list[[each data frame in list]][each column in data frame] <-
as.numberic(my.list[[each data frame in list]][each column in data frame])
如果您能以任何方式帮助我,或者知道任何可以帮助我的资源,我将不胜感激。
背景:
我的数据框的结构如下例所示,其中我有 5 种栖息地类型以及有关单个物种的栖息地范围延伸到 n 面积的信息:
# Example data
spp.1.data <- data.frame(Habitat.A = c(100,45,0,9,0), Habitat.B = c(0,0,203,45,89), Habitat.C = c(80,22,8,9,20), Habitat.D = c(8,59,77,83,69), Habitat.E = c(23,15,99,0,10))
我有多个具有上述结构的数据框,已分配给列表对象:
all.spp.data <- list(spp.1.data, spp.2.data, spp.1.data...n)
然后我试图将所有数据帧强制转换为 as.numeric() 以便我可以创建栖息地使用百分比的数据帧,即:
# data, which is now numeric as per Phil's code ;)
data.numeric <- lapply(data, function(x) {
x[] <- lapply(x, as.numeric)
x
})
> head(data.numeric[[1]])
Habitat.A Habitat.B Habitat.C Habitat.D Habitat.E
1 100 0 80 8 23
2 45 0 22 59 15
3 0 203 8 77 99
4 9 45 9 83 0
5 0 89 20 69 10
编辑:我想总结所有数据帧中的每一行
# Add row at the end of each data frame populated by rowSums()
f <- function(i){
data.numeric[[i]]$Sums <- rowSums(data.numeric[[i]])
data.numeric[[i]]
}
data.numeric.SUM <- lapply(seq_along(data.numeric), f)
head(data.numeric.SUM[[1]])
Habitat.A Habitat.B Habitat.C Habitat.D Habitat.E Sums
1 100 0 80 8 23 211
2 45 0 22 59 15 141
3 0 203 8 77 99 387
4 9 45 9 83 0 146
5 0 89 20 69 10 188
编辑:这是我用来将数据框中的值转换为使用的栖息地百分比的代码
# Used Phil's logic to convert all numbers in percentages
data.numeric.SUM.perc <- lapply(data.numeric.SUM,
function(x) {
x[] <- (x[]/x[,6])*100
x
})
Perc.Habitat.A Perc.Habitat.B Perc.Habitat.C Perc.Habitat.D Perc.Habitat.E
1 47 32 0 6 0
2 0 0 52 31 47
3 38 16 2 6 11
4 4 42 20 57 37
5 11 11 26 0 5
6 100 100 100 100 100
这仍然不是最简洁的方法,但它对我有用。
感谢 Phil、Val 和 Leo P 帮助解决这个问题。
【问题讨论】:
-
您可以使用嵌套的
lapply调用循环遍历列表中的data.frames 列。all.spp.data <- lapply(all.spp.data, function(x) lapply(x, as.numeric))