1

I'm quite new to R so please excuse me if what I'm asking is somewhat trivial. So, I acquired a csv file containing something like this from an image analysis program:

FRAME      OBJECT_IS_IN_TARGET_AREA
1          0
2          1
5          1
6          0
7          0
...        ...
241        1

As you can see, there is no row for frame 3 and 4 and there might be rows missing further down until frame 241. Now, is there a way to complement the dataframe with the missing rows to receive a consecutive sequence of numbers ranging from 1 to 241 and assign each complemented row N/A for OBJECT_IS_IN_TARGET_AREA? The data frame should look like this in the end:

FRAME      OBJECT_IS_IN_TARGET_AREA
1          0
2          1
3          N/A
4          N/A
5          1
6          0
7          0
...        ...
241        1

Sadly, it is not possible to acquire these values from the image analysis program directly so I'd have to add them manually. Since I have a lot of these sequences this would be very tideous work. This is why I opted for R. Hope you can help me out.

Great Thanks,

E.

eFFecX
  • 65
  • 4

3 Answers3

4

You can use complete from library tidyr. Assuming your data frame name is df,

library(tidyr)
df %>% complete(FRAME=c(1:241)) -> df

should do the intended work.

Nuclear03020704
  • 549
  • 9
  • 22
2

I think you can do this using baseR:

Frame <- seq(241)
df <- data.frame(Frame=Frame)
df$OBJECT_IS_IN_TARGET_AREA <- ifelse(df$Frame %in% yourCSV$Frame, yourCSV$OBJECT_IS_IN_TARGET_AREA, NA)

Now df will be your complemented data frame with NA for objects not in your Frame and values of OBJECT_IS_IN_TARGET_AREA for values in your csv Frame.

A sample of yourCSV dataframe

yourCSV <- data.frame(Frame=c(1,2,3,10,241), OBJECT_IS_IN_TARGET_AREA=c(1,2,3,4,5))
deepseefan
  • 3,701
  • 3
  • 18
  • 31
1

Base R solution:

df <- merge(data.frame(FRAME = c(1:nrow(df))), df, by = "FRAME", all.x = TRUE)
hello_friend
  • 5,682
  • 1
  • 11
  • 15