简体   繁体   English

在R中,如何根据另一列的子集定义df中的新列?

[英]In R, how do you define a new column in a df as a function of a subset of another column?

I have time series data in a data frame. 我在数据框中有时间序列数据。 Let's say I have one column of dates, one column of values, and I want to create a new column that is the sum of all values before the date index. 假设我有一列日期,一列值,并且我想创建一个新列,该列是日期索引之前所有值的总和。 Is there a better solution than using a for loop? 有没有比使用for循环更好的解决方案?

For example: 例如:

table = data.frame(date=seq(1,5),values=c(3,2,4,1,5))
table$sum = ...??

For this you can use cumsum : 为此,您可以使用cumsum

table = transform(table, sum_value = cumsum(values))
table
  date values sum_value
1    1      3         3
2    2      2         5
3    3      4         9
4    4      1        10
5    5      5        15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 您如何根据每行的唯一子集的函数定义列? - How do you define a column based on a function of a unique subset for each row? 如何通过函数自变量基于提供的列名对R数据帧进行子集化? - how do you subset R data frame based on provided column names via a function argument? R 中有没有办法根据另一个 df 在 df 上计算新列? - Is there a way in R to compute a new column on a df based on another df? 如何在R的新列中保存经过过滤的子集? - How to save a filtered subset in R in a new column? R,与vector相比,如何根据现有列创建新的df列? - In R, how do I create a new df column based on an existing column compared to a vector? 如何传递R函数参数来子集列 - How to pass an R function argument to subset a column 对于 R 中的缺失值,如何获取一个列的子集并将其放入一个包含 0 而不是 NA 的新列中? - How do I take a subset of a column and make it into a new column with 0s instead of NAs for missing values in R? 是否有 R function 将向量应用于 df 中的列并创建新列? - Is there an R function to apply a vector to a column in a df, and create new columns? 如何根据DF2中的重要变量对DF1中的列变量进行子集化? - How do I subset column variables in DF1 based on the important variables I got in DF2? 我如何 plot 列子集与另一列的平均值? - How do I plot an average of a column subset against another column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM