-3

I have a data frame in R that I've edited to look like the following:

enter image description here

I would like to change the cells in column 2 with an 'x' to match the word at the top of the list of x's. For example, I would like column 2 rows 8-20 to list the word "farm_working_expenses", column 2 rows 22-27 to list the word "feed_expenses", etc.

Is there any way to edit the 'x' cells in the data frame to match the contents of a previous cell in the same column?

dj.bmw
  • 3
  • 1
  • Are you creating this data frame or trying to make changes to some data. Posting some sample code will get you a better answer. – Kevin Jul 13 '17 at 21:52
  • I'm trying to make changes to data that I imported in from an excel file. – dj.bmw Jul 13 '17 at 22:30
  • Replace your `x`'s with `NA`'s, then refer to this question: https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value – Scarabee Jul 13 '17 at 23:42

1 Answers1

0

dplyr::na_if() can be used to replace x with NA.

data1 <- data.frame(col1 = LETTERS[1:10], 
                    col2 = c('val1',rep('x',3),'val2',rep('x',3),'val3','x'))
data1
#    col1 col2
# 1     A val1
# 2     B    x
# 3     C    x
# 4     D    x
# 5     E val2
# 6     F    x
# 7     G    x
# 8     H    x
# 9     I val3
# 10    J    x


data1$col2 <- dplyr::na_if(data1$col2, 'x')

Using tidyr::fill(), last observation can be carried forward till a new value appears in the same column.

data1 %>% tidyr::fill(col2)
#    col1 col2
# 1     A val1
# 2     B val1
# 3     C val1
# 4     D val1
# 5     E val2
# 6     F val2
# 7     G val2
# 8     H val2
# 9     I val3
# 10    J val3

zoo::na.locf can also be used for similar purpose.

data1 <- data.frame(col1 = LETTERS[1:10], 
                col2 = c('val1',rep(NA,3),'val2',rep(NA,3),'val3',NA))
data1
#    col1 col2
# 1     A val1
# 2     B <NA>
# 3     C <NA>
# 4     D <NA>
# 5     E val2
# 6     F <NA>
# 7     G <NA>
# 8     H <NA>
# 9     I val3
# 10    J <NA>

zoo::na.locf(data1$col2)
# [1] val1 val1 val1 val1 val2 val2 val2 val2 val3 val3
Prradep
  • 5,506
  • 5
  • 43
  • 84