Appreciate your help on this. Been working on this for the whole day with no end in sight.
I have a csv file with rows coming through as multi-line per rows. Would like to expand the rest of the columns to accommodate the 'multi' rows.
I tried
Here is an example
df <- data.frame(email = c('[email protected]','[email protected]','[email protected]'),
ip = c('1 1 2 2 3','2 2 2','3 3 3'),
other = c('x','y','z'))
#looks likes this
email ip other
1 [email protected] 1 1 2 2 3 x
2 [email protected] 2 2 2 y
3 [email protected] 3 3 3 z
desired outcome
> df_to_be
email ip other
1 [email protected] 1 x
2 [email protected] 1 x
3 [email protected] 2 x
4 [email protected] 2 x
5 [email protected] 3 x
6 [email protected] 2 y
7 [email protected] 2 y
8 [email protected] 2 y
9 [email protected] 3 z
10 [email protected] 3 z
11 [email protected] 3 z
logic to construct
Email1 repeats 5 times due to the number of 'multi' lines for the first row. Email2 repeats 3 times due to the number of 'multi' lines for the 2nd row. Email3 repeats 3 times due to the number of 'multi' lines for the 3rd row.
similarly to other column
My Attempts
#function to recreate table based on new row count
repFunc <- function(df, multi_row_c){
cols_rep <- names(df[which(!names(df) %in% c(multi_row_c))]) #columns to repeat
vec_rep = str_count(df[,multi_row_c],coll(" "))+1 #vector of number of repeats per row for multi_row_c
r1 = 1:nrow(df) #row index to repeat
print('column names to repeat')
print(cols_rep)
print('number of repeats per row')
print(vec_rep)
print('row index to repeat')
print(r1)
for (i in 1:length(cols_rep)) {
print(df[,cols_rep[i]])
# o<-rep(df[r1,cols_rep[i]],vec_rep)
}
# return(o)
}
repFunc(df,'ip')