AtmoSci
AtmoSci

Reputation: 127

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

I want to transform the third dimension of data for my 3 dimensional array-

> my.array
, , 1

   0 90 45
1 -1 -4 -7
2 -2 -5 -8
3 -3 -6 -9

The column names are latitudes and the row names are based on a height above ground level. The function that needs to be performed depends on latitude so, is there a way that I can call the column name and use it as an integer in the equation? If not, is there another way that you would suggest?

For example-

>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)

The ultimate goal would be to get it to process each value using the column name, so the function would compute as such for my.array[1,2,1] -

y <- -4*sin(90)
x <- -4*cos(90)

Thanks in advance for the help.

Upvotes: 0

Views: 53

Answers (2)

Jinjin
Jinjin

Reputation: 610

For anyone who come across this topic later. Not sure where your x of my.fun come from. Generally, you can access columns by names using lapply(). Just like below:

lapply(1, my.fun(i, df), df=yourdf)[[1]]

Here in lapply(), i is a must have and just pass your dataframe as an additional parameter df and then you are able to reference any columns using df$any_column_you_want inside the function.

Upvotes: 0

Heroka
Heroka

Reputation: 13149

Personally, I'm not a fan of storing that much information in column names, so I wrote a solution thats a bit different than you asked. As you've probably noticed, R and numerical column names don't always work well. So here is a solution that turns your data to a long format, and calculates the x's and y's. I kept my.array as a list, so the solution should be easily scalable.

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

Upvotes: 1

Related Questions