如何从R的不同起点开始求和

时间:2016-10-06 21:26:53

标签: r

所以我想读取数据并对18000点数据中的一列进行求和。事情是求和需要变量Tc然后再减去五次迭代。我不知道如何让它从它的总和5个数据点开始,所以它没有给我一个错误,即在前4个数据点中没有任何东西可以减去。

以下是一小部分数据:

const initialUserObj = { userId: 0, username: 'admin' };

const getUserGroup = function(id) {
  console.log(`Requesting user group for user with id ${id}`); // debug only

  const typeAdmin = { group: 'Administrator', rights: 'all' };
  const typeUser = { group: 'User', rights: 'restricted' };
  const timeout = Math.floor(Math.random() * 5000);

  return new Promise((resolve, reject) => {
    // Simulated API call with timeout
    setTimeout(() => {
      resolve(id === 0 ? typeAdmin : typeUser);
    }, timeout);
  });
}

const getUserDetails = function(id) {
  console.log(`Requesting user details for user with id ${id}`); // debug only

  const timeout = Math.floor(Math.random() * 5000);

  return new Promise((resolve, reject) => {
    // Simulated API call with timeout
    setTimeout(() => {
      resolve({ fullName: id === 0 ? 'Administator himself' : 'Some User' });
    }, timeout);
  });
}

Rx.Observable.of(initialUserObj)
  .flatMap(user => {
    return Rx.Observable.fromPromise(getUserGroup(user.userId))
      .map(group => Object.assign({}, user, group));
  })
  .flatMap(user => {
    return Rx.Observable.fromPromise(getUserDetails(user.userId))
      .map(details => Object.assign({}, user, details));
  })
  .subscribe(x => console.log(x));

以下是代码:

 head(data)
               Time   Record   Ux   Uy    Uz    Ts       Tc       Tn       To       Tp  Tq
1 2016-09-07 09:00:00.1 38651948 0.46 1.21 -0.26 19.53 19.31726 20.43197 19.39093 19.54993 NAN
2 2016-09-07 09:00:00.2 38651949 0.53 1.24 -0.24 19.48 19.30391 20.43744 19.37996 19.51704 NAN
3 2016-09-07 09:00:00.3 38651950 0.53 1.24 -0.24 19.48 19.31249 20.43269  19.3752 19.44648 NAN
4 2016-09-07 09:00:00.4 38651951 0.53 1.24 -0.24 19.48 19.30391 20.40221 19.33919 19.41596 NAN
5 2016-09-07 09:00:00.5 38651952 0.53 1.24 -0.24 19.48 19.24906 20.36079 19.31178 19.38068 NAN
6 2016-09-07 09:00:00.6 38651953 0.51 1.28 -0.28 19.44 19.20519 20.32008 19.30629 19.42693 NAN

1 个答案:

答案 0 :(得分:0)

欢迎来到stackoverflow!

我建议你在这里为下一个问题制作一个更可重现的例子(见here)。

要回答您的问题,您可以在for循环中进行此操作,因为您目前正在进行或以更有效的方式进行操作;使用一种apply函数(此处:lapply)。您可以阅读有关这些函数的更多信息here

创建数据集:

set.seed(1)
Tc<-rnorm(18000) 

lapply功能。请注意,我们从6开始,因为Tc[5] - Tc[c(5-5)]只会返回Tc[5]

sum<-unlist(lapply(6:18000,function(x) Tc[x]-Tc[c(x-5)]))

完成!

在控制台中输入验证功能:

> head(sum)
[1] -0.1940146  0.3037857  1.5739533 -1.0194995 -0.6348962  2.3322496
> Tc[6]-Tc[1]
[1] -0.1940146