创建一个向量,其连续元素作为相邻列中的相应值重复多次 [英] Creating a vector, sequential elements of which are repeated that many times as the corresponding values in neighbouring columns

查看:21
本文介绍了创建一个向量,其连续元素作为相邻列中的相应值重复多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例数据框中,输出向量应为 [1] 1,1,1,2,1,1,1,2,2,3,3,3,4,5,5,5,5,1,1,2,3,3,3

In the below sample data frame, the output vector should be [1] 1,1,1,2,1,1,1,2,2,3,3,3,4,5,5,5,5,1,1,2,3,3,3

P   N   N+1 N+2 N+3 N+4
2   3   1   1   2   1
5   3   2   3   1   4
3   2   1   3   4   5

解释:

  • P 中的值指示应该读取数据框值到右侧多远.seq(P) 中的值应该重复多次.
  • P 的第一个值是 2,这意味着在 seq(2)(即 1,2)中,第一个元素应该重复 3 次,第二个元素应该重复 1 次.
  • 这是因为 P 的值 (2) 表示读取它右侧的前两个元素.右侧的那些值本身表示 2 的顺序元素应该重复多少次.

推荐答案

这里的一个选项是使用 apply MARGIN = 1 循环遍历行,然后,得到seq 基于第一个元素,即 'P',复制 seq uence 与 'N' 列的相应值,该值是该序列的子集

An option here would be to loop over the rows with apply MARGIN = 1, then, get the seq based on the first element i.e. 'P', replicate the sequence with the corresponding values of 'N' columns subsetted with that sequence

unlist(apply(df1, 1, function(x)  {
        i1 <- seq(x[1])
        rep(i1, x[-1][i1])
       }))

-输出

#[1] 1 1 1 2 1 1 1 2 2 3 3 3 4 5 5 5 5 1 1 2 3 3 3

数据

df1 <- structure(list(P = c(2L, 5L, 3L), N = c(3L, 3L, 2L), `N+1` = c(1L, 
2L, 1L), `N+2` = c(1L, 3L, 3L), `N+3` = c(2L, 1L, 4L), `N+4` = c(1L, 
4L, 5L)), class = "data.frame", row.names = c(NA, -3L))

这篇关于创建一个向量,其连续元素作为相邻列中的相应值重复多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆