首页 > 解决方案 > R重复或循环data.frame以适应每行多行

问题描述

感谢您对此的帮助。一整天都在为此工作,看不到尽头。

我有一个 csv 文件,其中每行多行。想要扩展其余列以容纳“多”行。

我试过了

这是一个例子

df <- data.frame(email = c('email1@email.com','email2@email.com','email3@email.com'),
                    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 email1@email.com 1 1 2 2 3     x
2 email2@email.com     2 2 2     y
3 email3@email.com     3 3 3     z

期望的结果

> df_to_be
              email ip other
1  email1@email.com  1     x
2  email1@email.com  1     x
3  email1@email.com  2     x
4  email1@email.com  2     x
5  email1@email.com  3     x
6  email2@email.com  2     y
7  email2@email.com  2     y
8  email2@email.com  2     y
9  email3@email.com  3     z
10 email3@email.com  3     z
11 email3@email.com  3     z

构造逻辑

由于第一行的“多”行数,Email1 重复 5 次。由于第二行的“多”行数,Email2 重复 3 次。由于第三行的“多”行数,Email3 重复了 3 次。

与其他列类似

我的尝试

#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')

标签: rmatrixrepeatdata-manipulationmultiline

解决方案


推荐阅读