Misc
Misc

Reputation: 645

if/else statement using lapply to iterate through rows in list of data frames in R

I don't think this is a hard question, but I simply cannot figure this out and couldn't find anything on stacks (hopefully I'm not duplicating). I'm trying to change my nested for loops into lapply statements using if/else. I have a list of data frames but have not figured out how to access the rows like I can in nested for loops. I'm using the bearingDelta column to populate a new list with either a 1 or 0 depending on whether the value of the bearingDelta column is greater or less than 119.9. Also, I realize this question may seem similar to a question I posted recently, but I think it's different enough to live.

data:

lat <- c(32.87707, 32.87708, 32.87694, 32.87726, 32.87469)
lon <- c(-117.2386, -117.2334, -117.2378, -117.2356, -117.2329)
bearingDelta <- c(180, 49, 23, 119, 129)
df <- data.frame(cbind(bearingDelta, lat, lon))
df.list <- list(df, df, df, df)

nested loop:

over120 <- list()
for (i in 1:length(tripList)) {
  for (j in 1:nrow(tripList[[i]])) {
 if (tripList[[i]][j, c("bearingDelta")] <= 119.9) {
   over120[[i]][j] <- 0 }
 else {
   over120[[i]][j] <- 1 }
  }
}

lapply (something like this is what I'm trying to get at).

over120 <- lapply(tripList, if (tripList[[i]][j, c("bearingDelta")] <= 119.9)     over120[[i]][j] <- 0 
   else over120[[i]][j] <- 1)

the desired output for this sample dataset would look like this:

> over120
[[1]]
[1] 1  0  0  0  1

[[2]]
[1] 1  0  0  0  1

[[3]]
[1] 1  0  0  0  1

[[4]]
[1] 1  0  0  0  1

Upvotes: 0

Views: 1463

Answers (1)

alexwhan
alexwhan

Reputation: 16026

No need for if:

lapply(df.list, function(x) as.integer(x$bearingDelta >= 119.9))
# [[1]]
# [1] 1 0 0 0 1
# 
# [[2]]
# [1] 1 0 0 0 1
# 
# [[3]]
# [1] 1 0 0 0 1
# 
# [[4]]
# [1] 1 0 0 0 1

Upvotes: 3

Related Questions