r - 如何通过重复 1 列并按顺序重复原始数据框的第 2 列来创建新的数据框?
问题描述
我试图通过重复 original-df 第 1 列中的值并将它们对应于 original-df 第 2 列中的重复值来创建新的数据框。但是,每列的值应该以不同的方式重复。例如,来自 original-df 第 1 列的值将重复为 1,2,3,1,2,3,1,2,3。其中原始df第2列的值应重复为1,1,1,2,2,2,3,3,3。
#here is original df
df1<-data.frame(x=1:3, y=10:12)
#I've tried the followig:
data.frame(x=df1$x,y=df1[,2])->df2
range<-1:3
data.frame(x=df1$x,y=df1$y[range,2])->df3
#I then tried this:
rep(df1$x,df1$y[l,2])->df4
#output either looks like this:
x y
1 1 10
2 2 11
3 3 12
#Or I receive an error message:
Error in df1$y[1, 2] : incorrect number of dimensions
#I expect data output to look like this:
x y
1 10
2 10
3 10
1 11
2 11
3 11
1 12
2 12
3 12
解决方案
一个选择是expand
library(tidyr)
expand(df1, x, y)
或expand.grid
从base R
do.call(expand.grid, df1)
推荐阅读
- excel - 循环不进一步
- macos - LLDB 和库函数的内存地址
- javascript - 粘贴前替换剪贴板中的特殊字符
- mysql - docker-compose up 后,MySQL 容器在“X 插件准备好连接”处停止
- javascript - 纱线升级后的TypeERROR(ReactJS项目)
- java - Spring Data JPA - 命名查询忽略空参数
- python - 绘制按年份分组的经纬度热图
- python-3.x - 如何使这个“倒数函数起作用”,python 3?
- java - 使用 Puppeteer,如何打开页面、获取数据并在循环中使用该数据导航到上一页
- imagemagick - imagemagick 将 RGB PNG 转换为 CMYK PDF