r - 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')
解决方案
推荐阅读
- assembly - 如何在 Risc v 汇编代码中提取位
- python - 在 np.where() 上的 true_divide 中遇到 Numpy 除以零
- flutter - 折线工具在颤振中的问题
- python - python中与熊猫的父子关系
- jquery - 如何根据Datatables jquery中的单元格值禁用行复选框
- html - 如何找出导航的宽度,以便将其设置为与图像完全相同?
- javascript - FirebaseError:Firebase 存储:字符串与格式“base64”不匹配:找到无效字符
- node.js - 在 Heroku 上成功部署我的 node.js 缺少什么
- schema - BizTalk Rule Composer 在添加新词汇后不更新规则
- python - 熊猫从索引中删除字符