在 r 中使用 apply() 函数时为每个值调用列名

Call a column name when for each value when using the apply() function in r

我想为我的三维数组转换第三维数据-

> 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