减去R中的列

时间:2018-03-10 01:39:16

标签: r dataframe

我有以下数据框:

Name,2014,2015,2016,2017,2018
Brad,100,200,342,532,65
Tom,54,2,523,121,200
Uma,200,221,225,229,250

我要做的是每年从前一栏减去这个:

Name,2014,2015,2016,2017,2018
Brad,0,100,142,190,-467

我想自动完成,而不是这样:

(df$"2003" - df$"2002")

怎么可能?我是R的新手,对不起。感谢

2 个答案:

答案 0 :(得分:1)

您可能需要类似

的内容
# this is your data
df <- data.frame("2014"=c(100,54,200),
             "2015"=c(200,2,221),
             "2016"=c(342,523,225),
             "2017"=c(532,121,229),
             "2018"=c(65,200,250),
             row.names=c("Brad","Tom","Uma"))

df     
#      X2014 X2015 X2016 X2017 X2018
# Brad   100   200   342   532    65
# Tom     54     2   523   121   200
# Uma    200   221   225   229   250

...然后你这样做

df[,-1] - df[,-5]
#      X2015 X2016 X2017 X2018
# Brad   100   142   190  -467
# Tom    -52   521  -402    79
# Uma     21     4     4    21

df[,-1]给出了data.frame的每一列,除了第一列,df[,-5]给出了除第五列之外的每一列......从那里,它是简单的减法。< / p>

答案 1 :(得分:0)

df <- structure(list(X2014 = c(100, 54, 200), X2015 = c(200, 2, 221
), X2016 = c(342, 523, 225), X2017 = c(532, 121, 229), X2018 = c(65, 
200, 250)), .Names = c("X2014", "X2015", "X2016", "X2017", "X2018"
), row.names = c("Brad", "Tom", "Uma"), class = "data.frame")

解决方案1 ​​

由于2014年的值无论如何都是零,你可以完全删除整个列。

data.frame(t(apply(df, 1, diff)))

解决方案2

使用dplyr

library(dplyr)
df <- data.frame(t(df)) %>% mutate_all(function(x) x - lag(x,default =x[1]))
df <- data.frame(t(df))