The current issue I am facing is that I have generated a list of row numbers based on the location of specific values within a table. This is as follows:
row_values <- which(table[,1] == "place of work :")
This leaves me with a list of all the row numbers in which "place of work" appears:
[1] 1 406 811 1216 1621 2026 2431 2836 3241 3646 4051 4456 4861 5266 5671 6076 6481 6886 7291 7696 8101 8506 8911 9316 9721 10126
[27] 10531 10936 11341 11746 12151 12556
This is 32 entries in total. I then also have another table which contains a number of codes (32 in total):
Area Code (Origin)
[1,] "E41000293"
[2,] "E41000294"
[3,] "E41000295"
[4,] "E41000296"
[5,] "E41000297"
[6,] "E41000298"
[7,] "E41000299"
[8,] "E41000300"
[9,] "E41000301"
[10,] "E41000302"
[11,] "E41000303"
[12,] "E41000304"
[13,] "E41000305"
[14,] "E41000306"
[15,] "E41000307"
[16,] "E41000308"
[17,] "E41000309"
[18,] "E41000310"
[19,] "E41000311"
[20,] "E41000312"
[21,] "E41000313"
[22,] "E41000314"
[23,] "E41000315"
[24,] "E41000316"
[25,] "E41000317"
[26,] "E41000318"
[27,] "E41000319"
[28,] "E41000320"
[29,] "E41000321"
[30,] "E41000322"
[31,] "E41000323"
[32,] "E41000324"
I need to find a way to paste those "Area Code (Origin)" values into the original table in every row between what the row_values as shown. These would sit in a blank column I have called "Area Codes (Destinations)". I.e, E41000293 should sit in the Area Code Destinations Column for every row from 1 to 405, E41000294 should sit from 406 to 810 ect.
Any help with this would be greatly appreciated as I am at a loss for how best to approach this.
Thanks, Joe
CodePudding user response:
You can use cumsum
in a clever way to achieve this:
library(dplyr)
table %>%
group_by(grp = cumsum(text == "place of work :")) %>% #change "text" to your column name
mutate(Area_Code = Area[grp,]) %>% #change Area to your table name
ungroup() %>%
select(-grp)
All that's left to do is change the table names and column names to fit your problem.
CodePudding user response:
This should do it :
for (i in 1:length(row_values)) {
if (i == length(row_values)-1) {
table[c(row_values[i]:(row_values[i 1])),'Area Codes (Destinations)'] = Areacode[i]
} else if (i <length(row_values)-1)) {
table[c(row_values[i]:(row_values[i 1]-1)),'Area Codes (Destinations)'] = Areacode[i]
}else{}
}