Home > Blockchain >  R: How do I create a new row, then add some cells from the previous row, iterating through the whole
R: How do I create a new row, then add some cells from the previous row, iterating through the whole

Time:07-01

I'd like to take each cell from V9-13 here and create a new row below each existing row, adding the values from cells V9-13 to the new row. This means that row 1 will have values V1-V8, then the new row below it will have V9-V13 from row 1 in the V1-V5 columns of that row.

Here's an image of the sheet

{

library("readxl")
library("dplyr")

text_data <- read.delim("C:\\Users\\Kavin Kadam\\Desktop\\UBC\\PCIGR\\IoliteOutlier\\Individual Answers_472.txt", skip=19, header=FALSE)

x<-(nrow(text_data))

for (i in 1:x) {
  text_data_refined<-dplyr::add_row(
    text_data,
    V1 = text_data$V9[i-1],
    V2 = text_data$V10[i-1],
    V3 = text_data$V11[i-1],
    V4 = text_data$V12[i-1],
    V5 = text_data$V13[i-1],
    .after = text_data_refined[i,]
    )
  }

}

The sample output would be as in this image - it takes the V9-V13 from the previous row and adds it to the new row here:

here

CodePudding user response:

I would add a row identifer, use bind_rows(), and then arrange by that row identifier.

text_data <- text_data %>% mutate(id=row_number())
bind_rows(
  df %>% relocate(id),
  df %>% select(id, V9:V13) %>% rename_with(~c("id", paste0("V",1:5)))
) %>% arrange(id)

CodePudding user response:

text_data<-as.matrix(text_data)
n<-nrow(text_data)

#initialize new matrix
new_data<-matrix(NA, nrow=2*n, ncol=8)

#fill values
new_data[seq(from=1, to=2*n, by=2), 1:8]<-text_data[,1:8]
new_data[seq(from=2, to=2*n, by=2), 1:5]<-text_data[,9:13]
  • Related