[英]How to sum values from two adjacent columns in a data.frame in R but keep 0s as such?
I have a data.frame with absence/presence data (0/1) for a group of animals, with columns as years and rows as individuals.我有一个包含一组动物的缺席/存在数据 (0/1) 的 data.frame,列是年份,行是个体。
My data:我的数据:
df <- data.frame(Year1 = c('1','0','0','0','0','0'),
Year2 = c('1','1','1','0','0','0'),
Year3 = c('1','1','1','1','1','0'),
Year4 = c('0','1','1','1','1','1'),
Year5 = c('0','0','1','1','1','1'),
Year6 = c('0','0','0','0','0','0'))
df
Year1 Year2 Year3 Year4 Year5 Year6
1: 1 1 1 0 0 0
2: 0 1 1 1 0 0
3: 0 1 1 1 1 0
4: 0 0 1 1 1 0
5: 0 0 1 1 1 0
6: 0 0 0 1 1 0
What I would like to do is to calculate the age per individual per year, meaning I would like to add col1 to col2, then that that sum to col3, and so on, so that the above data frame becomes:我想要做的是计算每个人每年的年龄,这意味着我想将 col1 添加到 col2,然后将总和添加到 col3,依此类推,使上述数据框变为:
df
Year1 Year2 Year3 Year4 Year5 Year6
1: 1 2 3 0 0 0
2: 0 1 2 3 0 0
3: 0 1 2 3 4 0
4: 0 0 1 2 3 0
5: 0 0 1 2 3 0
6: 0 0 0 1 2 0
Importantly, zeros should remain zeros: once there is a column with a 0 after a sequence of non-zero values, the value should be 0 again, as the animal has died and does not continue in the population.重要的是,零应该保持为零:一旦在一系列非零值之后有一列带有 0 的列,该值应该再次为 0,因为动物已经死亡并且不会继续存在于种群中。
I have browsed many stackoverflow questions, eg:我浏览了许多 stackoverflow 问题,例如:
sum adjacent columns for each column in a matrix in R 对 R 中矩阵中每一列的相邻列求和
However, I could not find a solution that does the cut-off part after the individual has passed away (a 0 after 4 years of living means the animal has left the population and the age should no longer be recorded for that year).但是,我找不到在个体去世后进行截止部分的解决方案(4 年后的 0 表示该动物已离开种群并且不应再记录该年的年龄)。
Thank you in advance for your advice!预先感谢您的建议! :) :)
Here's a pretty simple way.这是一个非常简单的方法。 We do a cumulative sum by row, and multiply by the original data frame -- multiplying by 0 zeros out the 0 entries, and multiplying by 1 keeps the summed entries as-is.我们按行计算累积总和,然后乘以原始数据框——乘以 0 将 0 项归零,乘以 1 保持总和项保持原样。 Since you have quotes around your numbers making them character
class, we start by converting all your columns to numeric
:由于您的数字周围有引号使它们成为character
类,因此我们首先将您的所有列转换为numeric
:
df[] = lapply(df, as.numeric)
result = t(apply(df, 1, cumsum)) * df
result
# Year1 Year2 Year3 Year4 Year5 Year6
# 1 1 2 3 0 0 0
# 2 0 1 2 3 0 0
# 3 0 1 2 3 4 0
# 4 0 0 1 2 3 0
# 5 0 0 1 2 3 0
# 6 0 0 0 1 2 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.