0

I have a 3-dimensional array, the variables being x, y and z. x is a list of places, y is a list of time, and z is a list of names. The list of names do not start at the same initial time across the places:

x   y   z
x1  1   NA
x1  2   z2
x1  3   z3
x1  4   z1
x2  1   NA
x2  2   NA
x2  3   z5
x2  4   z3
x3  1   z3
x3  2   z1
x3  3   z2
x3  4   z2

How do I find the first z for every x? I want the output matrix or dataframe to be:

x  z
x1 z2
x2 z5
x3 z3
5
  • please provide some sample data, as I have no clue how your array looks like exactly. As far as it looks now, you have a simple matrix, not a 3D-array as data structure.
    – Joris Meys
    Apr 11, 2011 at 15:31
  • Is there any way to upload a sample data?
    – user702432
    Apr 11, 2011 at 15:52
  • Make a small reproducible example using matrix() or try dput(your.data). Apr 11, 2011 at 15:53
  • Okay, I just edited the original post including the sample data.
    – user702432
    Apr 11, 2011 at 16:05
  • now it looks like a dataframe (which is 2-dimensional, see the introduction to R for some examples on arrays).
    – Joris Meys
    Apr 11, 2011 at 16:05

2 Answers 2

1

EDITED, after example data was supplied

You can use function ddply() in package plyr

dat <- "x   y   z
x1  1   NA
x1  2   z2
x1  3   z3
x1  4   z1
x2  1   NA
x2  2   NA
x2  3   z5
x2  4   z3
x3  1   z3
x3  2   z1
x3  3   z2
x3  4   z2"

df <- read.table(textConnection(dat), header=TRUE, stringsAsFactors=FALSE)

library(plyr)
ddply(df, .(x), function(x)x[!is.na(x$z), ][1, "z"])

   x V1
1 x1 z2
2 x2 z5
3 x3 z3
0
0

If you don't want to use plyr

t(data.frame(lapply(split(df, as.factor(df$x)), function(k) head(k$z[!is.na(k$z)], 1))))

   [,1]
x1 "z2"
x2 "z5"
x3 "z3"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.