我想将第三维数据转换为我的三维数组-
> my.array
, , 1
0 90 45
1 -1 -4 -7
2 -2 -5 -8
3 -3 -6 -9
列名称是纬度,行名称基于距地面的高度。需要执行的函数取决于纬度,所以有没有办法可以调用列名称并将其用作方程中的整数?如果没有,您还有其他建议吗?
例如-
>my.fun <- function(x, current.column.name){
>y <- x*sin(current.column.name)
>x <- x*cos(current.column.name)
>}
>apply(my.array, c(1,2), my.fun)
最终目标是让它使用列名称处理每个值,因此该函数将像这样计算 my.array[1,2,1] -
y <- -4*sin(90)
x <- -4*cos(90)
提前感谢您的帮助。
就我个人而言,我不喜欢在列名称中存储那么多信息,因此我编写了一个与您要求的有点不同的解决方案。您可能已经注意到,R 和数字列名称并不总是有效。因此,这里有一个解决方案,可将数据转换为长格式,并计算 x 和 y。我将
my.array
保留为列表,因此该解决方案应该易于扩展。
my.array <- list('1'=read.table(text="0 90 45
1 -1 -4 -7
2 -2 -5 -8
3 -3 -6 -9",header=T,check.names=F))
library(reshape2)
melted_arrays <- lapply(my.array,function(x){
x <- data.frame(x, check.names=F)
x$height <- as.numeric(rownames(x))
melt_x <- melt(x,id.vars="height",variable.name="latitude")
melt_x$latitude <- as.numeric(as.character(melt_x$latitude))
melt_x$x <- with(melt_x, value*sin(latitude))
melt_x$y <- with(melt_x, value*cos(latitude))
return(melt_x)
})
> melted_arrays[[1]]
height latitude value x y
1 1 0 -1 0.000000 -1.000000
2 2 0 -2 0.000000 -2.000000
3 3 0 -3 0.000000 -3.000000
4 1 90 -4 -3.575987 1.792294
5 2 90 -5 -4.469983 2.240368
6 3 90 -6 -5.363980 2.688442
7 1 45 -7 -5.956325 -3.677254
8 2 45 -8 -6.807228 -4.202576
9 3 45 -9 -7.658132 -4.727898
对于后来遇到这个话题的人。不确定你的
x
的 my.fun
来自哪里。通常,您可以使用 lapply()
按名称访问列。就像下面这样:
lapply(1, my.fun(i, df), df=yourdf)[[1]]
在
lapply()
中,i
是必须具备的,只需将数据帧作为附加参数传递即可 df
,然后您就可以在函数内使用 df$any_column_you_want
引用任何列。